Python classes
definition:
Class ClassNane:
Statement block
- The class keyword must be used
- The class name must be named after the big hump
- After the class definition is completed, a class object is generated and bound to the class identifier ClassName
give an example:
class MyClass:
pass
Class object and class attribute
- Class object: a class object will be generated after the class definition is executed
- Class attributes: variables and methods in class definitions are class attributes
- Class variable: in the above example, x is a variable of MyClass
class MyClass:
”’A example of Class”’
x=’abc’
def foo(self):
print(‘foo method’)
In MyClass, x and foo are attributes of the class__ doc__ It is also a special property of a class
The foo method is an attribute of a class, like eat yes Human approach, however Every specific person can eat , that is eat It is the method that human examples can be mobilized.
Foo is a method, which is essentially a common function object function. It generally requires at least one parameter. The first formal parameter can be self (self is just a conventional identifier, which can be renamed). This parameter position is reserved for self.
instantiation
a=MyClass() #实例化
Using the above syntax, add a parenthesis after the class object name to call the class instantiation to complete the instantiation.
Instantiation is to really create an object (instance) of this class, for example:
tom=Person()
jerry=Person()
The tom and jerry above are instances of the Person class, and two instances are generated through instantiation.
Each instance obtained after instantiation is a different instance. Even if the same parameters are used for instantiation, different objects will be obtained.
After Python instantiation, it will automatically call__ init__ method. The first formal parameter of this method must be left to self, and other parameters are optional.
class Person:
def __ init__ (self,name,age):
self.name=name
self.age=age
def showage(self):
print(self.age,self.name)
t=Person(‘tom’,20)
j=Person(‘jerry’,18)
t,j
__ init__ method
MyClass() actually calls__ init__ (self) method can be undefined. If it is not defined, it will be called implicitly after instantiation.
Function: initialize instantiation