Python is an object-oriented language, and as an object-oriented feature-class is also available. It is worth noting that everything in Python is object, not like in C # for performance reasons, int is also an object in Python. (int is struct in C #)
How to define a class:
1 class Person : 2 Pass
Use class keyword, which defines a person class. But now this class is blank.
Next, define a constructor function
1 class Person : 2 def __init__ (self,name,age): 3 Self.name=name4 self.age=age
The function __init__ is the name of the constructor for a class in Python, and the name of any Python class constructor must be.
In the __init__ constructor, the first argument self refers to the instance. This is well understood, because the constructor is also an instance function. In Python, defining an instance function requires that the self parameter be filled in the first argument of the function.
Next, you define an instance function and a static function.
1 classPerson :2 def __init__(self,name,age):3Self.name=name4Self.age= Age5 6 defPrintname (self):7 Print(Self.name)8 9 defstaticprint ():Ten Print('This class\ ' s name was person')
The next step is to create a new instance of the class and call it.
1 Instance=person ('Tom')2instance.printname () 3 person.staticprint ()
The first line invokes the constructor of the person and assigns the instance to the instance variable. It is worth noting that there is no new keyword in python.
The second line invokes the instance method of the Printname. Output Tom.
The third line invokes the Staticprint static method of the person class, outputting this class's name is the person.
Python learning class definitions in -11.python