First, class definition:
Class < category name:
< statements >
Once instantiated, you can use its properties, and in fact, after you create a class, you can access its properties through the class name
If you modify its properties directly using the class name, it will directly affect the object that has already been instantiated
The principles of the definition of the Python class
attribute has no public or private claim.
There is no construction method, and the initial method is only the method that is executed when instantiated.
The method must be defined with the self argument, similar to this in Java.
The Python language is more flexible.
users.py file
The code is as follows |
Copy Code |
#!/usr/bin/env python #-*-Encoding:utf-8-*- Class User (object): "This is a user class" Name = "Tomas" Age = 0 def __init__ (self,age=22): Self.age = Age
def showage (self): Print Self.age
def showclassname (self): Print self.__class__.__name__
def showclassdoc (self): Print Self.__class__.__doc__users |
2.py file
The code is as follows |
Copy Code |
#!/usr/bin/env python #-*-Encoding:utf-8-*- Import Users
user = Users.user () User.showage () User.showclassname () User.showclassdoc () |
If you can call this class in users.py,
The code is as follows |
Copy Code |
user = User () |
The following summary
Private properties of the class:
__private_attrs a two underscore, declaring that the property is private and cannot be used or accessed directly outside the class
When used in methods inside a class Self.__private_attrs
Methods of the class
Within the class, use the DEF keyword to define a method for the class, unlike a generic function definition, the class method must contain the parameter self and the first argument
Private class method
__private_method The two underscore, declares the method as private and cannot be invoked outside the class
Calling Slef.__private_methods inside a class
The proprietary method of the class:
__init__ constructor, called when the object is generated
__del__ destructor, use when releasing objects
__repr__ Printing, converting
__SETITEM__ is assigned by index
__GETITEM__ Get values by index
__len__ Get length
__CMP__ comparison operations
__call__ function call
__add__ addition operation
__sub__ Subtraction Operation
__mul__ multiplication operation
__DIV__ in addition to operations
__MOD__ calculation
__pow__ said the Square