Python Notes-Class definitions
First, class definition:
Class < category name:
< statements >
After a class is instantiated, its properties can be used, and in fact, after a class is created, its properties can be accessed 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
Private properties of the class:
__private_attrs two underscores, declares that the property is private and cannot be used outside of the class or accessed directly
When used in methods inside a class Self.__private_attrs
Methods of the class
Inside the class, using the DEF keyword, you can define a method for a class that differs from a generic function definition, which must contain the parameter self, and is the first argument
Private class methods
__private_method two underscores, declares that the method is a private method and cannot be called outside of a class
Calling Slef.__private_methods inside a class
The proprietary methods of the class:
The __init__ constructor, which is called when the object is generated
__del__ destructors, using when releasing objects
__repr__ Printing, converting
__setitem__ Assignment by index
__getitem__ getting values by index
__len__ Get length
__CMP__ comparison operations
__call__ function call
__add__ Plus arithmetic
__SUB__ Reduction Operations
__mul__ Multiply operation
__DIV__ in addition to operations
__mod__ Calculating the remainder
__pow__ said Fang
Example:
#类定义
class people:
#定义基本属性
Name = ' '
Age = 0
#定义私有属性, private properties cannot be accessed directly outside the class
__weight = 0
#定义构造方法
def __init__ (self,n,a,w):
Self.name = n
Self.age = A
Self.__weight = W
def speak (self):
Print ("%s is speaking:i am%d years old"% (self.name,self.age))
p = people (' Tom ', 10,30)
P.speak ()
Python Notes-Class definitions