Since I've never been very clear about the programming idea of object-oriented classes and methods, I've made it a point to brush up on my knowledge of python-class, which I'll record and share here.
Concepts and examples of classes and methods
- Class: A collection of objects that describe objects that have the same properties and methods. It defines the attributes and methods common to every object in the collection. An object is an instance of a class.
- Methods: functions defined in the class.
- Class constructor __init__(): Classes have a special method called init() (constructor method) which is automatically called when the class is instantiated.
- Instance Variables: In the declaration of a class, attributes are represented by variables, such variables are called instance variables, an instance variable is a variable modified by self.
- Instantiation: creates an instance of a class, a concrete object of the class.
- Inheritance: A derived class inherits fields and methods from a base class. Inheritance also allows objects of a derived class to be treated as objects of a base class. For example, there is a design where an object of type Dog derives from the class Animal, which simulates an "is-a" relationship (example diagram, Dog is an Animal).
Class: class
Python's class is the equivalent of a family of multiple functions. If there is a person named f in this Myclass family, and if this f has the role of printing the weather, then if one day I need this f to print today's weather, then I have to call him by his full name in order to get him to print it for me, i.e., when I call him I.e. when calling him, you need to take his family name + his name.
- causality: Attributes are variables in this class. If the variables are items, then different attributes are different items in the big family
- methodologies: Methods are functions in this class. If functions are people, then different methods are different people in this big family.
MyClass instance:
#Myclass family, but this family has only one person f class MyClass: """A simple class instance.""" i = 12345 def f(self): return 'hello world' # Instantiate the class x = MyClass() # Access to class properties and methods print("Property i of class MyClass is:", ) # family x + item name i print("The output of method f of class MyClass is:", ()) # family x + name f
Output results:
2. Class constructor __init__()
Suppose init() is also a human being, but he is the family and outside liaison, when someone from the outside wants to call someone from his own family, he has to be told first, so as soon as a person from the family is called, then init() is executed first, and then he will go and tell that person who is called to execute the called.
init() instance:
class Complex: def __init__(self, realpart, imagpart): # must have a self argument. = realpart = imagpart x = Complex(3.0, -4.5) print(, ) # Output results: 3.0 -4.5
Output results:
3. Parameters of methods in the class self
Inside a class, the def keyword is used to define a method, and unlike a normal function definition, the class methodnecessarilyContains the parameter self, and is the first parameter, self represents an instance of the class.
- self:A method of a class differs from an ordinary function in only one particular way - it must have an additional first argument name, which by convention is self.
- instance of the class:It is the application of a class to an instance scenario, for example, if a function in a class is f, and if f has the ability to print the weather conditions at a certain time, then if I need f to print the weather at 12 o'clock today, then the action of letting it print the weather at 12 o'clock today is the instantiation of the class, so that the function in the class has the ability to turn into a real action.
Instantiate the instance:
# Class Definition class people: #Define basic attributes name = '' age = 0 # Define private attributes, which cannot be accessed directly from outside the class. #Define constructor methods def __init__(self,n,a): = n = a def speak(self): print("%says: I'm %d years old." %(,)) # Instantiate the class p = people('Python',10,30) ()
Output results:
4. Inheritance
If there are two families, one of which, family A, has begun to decline, and the other, family B, wants to inherit the goods and servants of family A, then the inheritance can be realized in the following way, where family A is the parent class and family B is the child class. In terms of usage, if family B can use family A's goods and servants at will.
class [subclass] ([parent class]).
- BaseClassName(the base class name in the example) must be defined in the same scope as the derived class. In addition to classes, expressions can be used, which is useful when the base class is defined in another module.
- python also supportsmulti-inheritanceThat is, you can inherit from more than one parent class. Inherit in the same way as single inheritance, in the following manner:
class [child]([parent]1, [parent]2, [parent]3).
Inheritance Example:
# Class Definition class people: #Define basic attributes name = '' age = 0 # Define private attributes, which cannot be accessed directly from outside the class. __weight = 0 #Define constructor methods def __init__(self,n,a,w): = n = a self.__weight = w def speak(self): print("%says: I'm %d years old." %(,)) #Single Inheritance Example class student(people): #student is the subclass and people is the parent class grade = '' def __init__(self,n,a,w,g): # Call the constructor of the parent class people.__init__(self,n,a,w) = g # Override methods of the parent class def speak(self): print("%says: I'm %d years old and I'm in %d grade."%(,,)) s = student('ken',10,60,3) ()
Running results:
5. Method rewriting
If the functionality of your parent's methods doesn't meet your needs, you can override your parent's methods in a subclass. I.e. if family B inherits family A, but family B has a servant who only knows how to sweep the floor, so family A brainwashes this person to know nothing, and then teaches this servant the skills of washing dishes and wiping the table, then this servant will only know how to wash dishes and wipe the table.
- The super() function is used to call a method of the parent class (superclass).
method overrides the instance:
class Parent: # Define the parent class def myMethod(self): print('Call parent class method') class Child(Parent): # Define subclasses def myMethod(self): print('Call subclass methods') c = Child() # Subclass instances () # Subclasses call overridden methods super(Child,c).myMethod() # Call methods that have been overridden in the parent class with a subclass object
Output results:
Special Properties and Methods of Classes
Private properties of a class
_private_attrs: Two underscores at the beginning declare that the attribute is private and cannot be used or accessed directly outside the class. When used in a method inside a class self.__private_attrs.
Private Property Instance:
class JustCounter: __secretCount = 0 # Private variables publicCount = 0 # Public variables def count(self): self.__secretCount += 1 += 1 print(self.__secretCount) counter = JustCounter() () () print() print(counter.__secretCount) # Error reported, instance can't access private variables
Output results:
Private methods of a class
- __private_method: starts with two underscores, declaring that the method is private and can only be called from within the class, not from outside. self.__private_methods.
Private method instances:
class Site: def __init__(self, name, url): = name # public self.__url = url # private def who(self): print('name : ', ) print('url : ', self.__url) def __foo(self): # Private methods print('This is a private method') def foo(self): # Public methods print('This is the public method') self.__foo() x = Site('Python', '') () # Normal output () # Normal output x.__foo() # Report an error
Output results:
Refer to study materials:
Python3 Object-Oriented
summarize
to this article on python class class and method of the article is introduced to this, more related python class class and method of content please search my previous articles or continue to browse the following related articles I hope you will support me more in the future!