The following small series for everyone to bring an article based on the Python3 class properties, methods, encapsulation, inheritance examples to explain. Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.
Python class
The classes in Python provide all the basic functions of object-oriented programming: The inheritance mechanism of classes allows for multiple base classes, and derived classes can overwrite any method in the base class, and the method can be called in the base class with the same name.
An object can contain any number and type of data.
Python classes are similar to C + + classes, providing encapsulation, inheritance, multiple inheritance, constructors, and destructors for classes.
In Python3, the top-most parent class of all classes is the object class, similar to Java, and if the class is defined without a parent class, the object class is its immediate parent class.
Class definition
The class definition syntax format is as follows:
Class classname:<statement-1>...<statement-n>
Class object: After a class has been created, it can be accessed through the class name, changed its properties, methods
Instance object: After the class is instantiated, its properties can be used to dynamically add properties (like JavaScript) to the instance object without affecting the class object.
Properties of the class
You can use the dot (.) To access the properties of an object
You can also access properties by using the following functions:
GetAttr (obj, name[, default]): Accessing the properties of an object
Hasattr (obj,name): Checks if a property exists
SetAttr (Obj,name,value): Sets a property. If the property does not exist, a new property is created
Delattr (obj, name): Delete attribute
Python built-in class properties
__DICT__: Properties of the Class (contains a dictionary, consisting of the data properties of the Class)
__DOC__: Document string for Class
__NAME__: Class name
__MODULE__: The module where the class definition resides (the full name of the class is ' __main__.classname ', if the class is in an import module mymod, then classname.__module__ equals Mymod)
__BASES__: All parent classes of a class make up elements (containing a tuple of all the parent classes)
Class Person: The "Person class" Def __init__ (self, name, age, gender): print (' Enter the initialization of person ') Self.name = name Self.age = Age Self.gender = Gender print (' Initialize of person left ') def getName (self): print (self.name) p = person (' ice ', 18, ' male ') pr int (p.name) # iceprint (p.age) # 18print (p.gender) # Man print (Hasattr (p, ' weight ')) # false# Add weight attribute to P p.weight = ' 70kg ' pri NT (Hasattr (p, ' weight ')) # Trueprint (GetAttr (p, ' name ')) # Iceprint (p.__dict__) # {' Age ': ' Gender ': ' Male ', ' name ': ' Ice ' }print (person.__name__) # personprint (person.__doc__) # Person class print (person.__dict__) # {' __doc__ ': ' Person class ', ' __ weakref__ ': <attribute ' __weakref__ ' of ' person ' objects>, ' __init__ ': <function person.__init__ at 0x000000000284e950>, ' getName ': <function person.getname at 0x000000000284ea60>, ' __dict__ ': <attribute ' _ _dict__ ' of ' person ' objects>, ' __module__ ': ' __main__ '}print (person.__mro__) # (<class ' __main__. Person ', <class ' object ' > ' Print (person.__bases__) # (<Class ' object ',) print (person.__module__) # __main__
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, and that the class method must contain the parameter self, which is the first argument.
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
__P__ in addition to operations
__mod__ Calculating the remainder
__pow__ said Fang
The __init__ () method is a special method, called a constructor or initialization method of a class, that is called when an instance of the class is created, similar to a constructor in C + +. Just rewrite the __init__ () method in your custom class.
Class Person: def __init__ (self, name, age, gender): print (' Enter person initialization ') self.name = name Self.age = Age Self.gender = gender print (' Initialize of person left ') def getName (self): print (self.name) # Person instance Object P = Person (' ice ', 18, ' Man ') print (p.name) print (p.age) print (P.gender) p.getname () # Enter the person's initialization # leave the person's initialization # ice# 18# Man # Ice
destructor __del__, __del__ is called when the object dies, and the __del__ method runs when the object is no longer being used:
Method
Instance method: can only be called through an instance, the first parameter defined by the instance method can only be referenced by the instance itself
Class Myclass: def foo (self): print ("Self", ' foo ') A=myclass () #既然是实例对象, then create Instance A.foo () #输出类里的函数地址print ( ID (a)) #输出类对象的地址 # The same as the result address
Class method: Defines a class method, to use the adorner @classmethod, the first parameter defined is a reference to the class object, which can be used directly from a class or instance
Class Myclass: @classmethod # class Decorator def foo2 (CLS): Print (ID (CLS), ' Foo2 ') #类对象, can be called directly, no need to instantiate print (ID ( Myclass), ' yy ') Myclass.foo2 () #直接可以调用
Static methods: Define static methods using adorner @staticmethod, no default mandatory parameters, direct call through class and instance
Class Myclass: @staticmethod # static method def Foo3 (): print (' Foo3 ') Myclass.foo3 () #没有参数a. Foo3 () #结果foo3
Encapsulation of classes
Python distinguishes the access rights of properties and methods by naming them by variable names, which are equivalent to public in C + + and Java
The private property of the class: __private_attrs: Two underscores, declares that the property is private and cannot be used outside of the class or accessed directly. Self.__private_attrs when used in methods inside a class.
Private method of the class: __private_method: Two underscore, declares that the method is a private method and cannot be called outside of a class. Calling Self.__private_methods inside a class
Although Python does not allow instantiated classes to access private data, you can use Object._classname__attrname to access properties. In fact, the implementation of Python's internal privatization only changed the Attrname attribute to _classname__attrname.
Class Demo: __id = 123456 def getId (self): return self.__idtemp = Demo () # Print (temp.__id) # error Attributeerro R: ' Demo ' object has no attribute ' __id ' Print (Temp.getid ()) # 123456print (temp._demo__id) # 123456
Inheritance of Classes
One of the main benefits of object-oriented programming is the reuse of code, and one way to implement this reuse is through inheritance mechanisms. Inheritance can be fully understood as a type and subtype relationship between classes.
What to note: Inherit the syntax class derived class name (base class name)://... The base class name is written in parentheses, and the base class is specified in the tuple at the time the class is defined.
Some of the characteristics of inheritance in Python:
1: The construction of the base class in inheritance (The __init__ () method) is not automatically called, it needs to be called specifically in the construction of its derived class. Use Super (). __init__ () or parentclassname.__init__ ()
2: When calling a method of the base class, you need to prefix the class name of the base class with the Self argument variable. Unlike calling a normal function in a class, you do not need to take the self argument
3:python always looks for a method of the corresponding type first, and if it cannot find the corresponding method in the derived class, it begins to look in the base class one by one. (Find the method that was called in this class before you can find it in the base class).
If more than one class is listed in an inheritance tuple, it is called "Multiple inheritance."
Grammar:
The declarations of derived classes are similar to their parent classes, and the list of inherited base classes follows the class name.
Polymorphic
If the functionality of the parent method does not meet the requirements, you can override the parent class's methods in the subclass. An overridden method that invokes its corresponding subclass when the instance object invokes the method
python3.3 class and inheritance small case
The classes in Hon provide all the basic functions of object-oriented programming: The inheritance mechanism of classes allows for multiple base classes, and derived classes can overwrite any method in the base class, and the method can be called in the base class with the same name.
Class Base: def __init__ (self): self.data=[] def Add (self,x): self.data.append (x) def addtwice (self,x): self.add (x) Self.add (x) # Child extends BaseClass child (Base): def Plus (self,a,b): Return A+bochild=child () ochild.add ("str1") Ochild.add (999) ochild.addtwice (4) print (ochild.data) print (Ochild.plus ( 2, 3))
An object can contain any number and type of data.
Python classes are similar to C + + classes, providing encapsulation, inheritance, multiple inheritance, constructors, and destructors for classes.
In Python3, the top-most parent class of all classes is the object class, similar to Java, and if the class is defined without a parent class, the object class is its immediate parent class.
Class definition
The class definition syntax format is as follows:
Class classname:<statement-1>...<statement-n>
Class object: After a class has been created, it can be accessed through the class name, changed its properties, methods
Instance object: After the class is instantiated, its properties can be used to dynamically add properties (like JavaScript) to the instance object without affecting the class object.
Properties of the class
You can use the dot (.) To access the properties of an object
You can also access properties by using the following functions:
GetAttr (obj, name[, default]): Accessing the properties of an object
Hasattr (obj,name): Checks if a property exists
SetAttr (Obj,name,value): Sets a property. If the property does not exist, a new property is created
Delattr (obj, name): Delete attribute
Python built-in class properties
__DICT__: Properties of the Class (contains a dictionary, consisting of the data properties of the Class)
__DOC__: Document string for Class
__NAME__: Class name
__MODULE__: The module where the class definition resides (the full name of the class is ' __main__.classname ', if the class is in an import module mymod, then classname.__module__ equals Mymod)
__BASES__: All parent classes of a class make up elements (containing a tuple of all the parent classes)
Class Person: The "Person class" Def __init__ (self, name, age, gender): print (' Enter the initialization of person ') Self.name = name Self.age = Age Self.gender = Gender print (' Initialize of person left ') def getName (self): print (self.name) p = person (' ice ', 18, ' male ') pr int (p.name) # iceprint (p.age) # 18print (p.gender) # Man print (Hasattr (p, ' weight ')) # false# Add weight attribute to P p.weight = ' 70kg ' pri NT (Hasattr (p, ' weight ')) # Trueprint (GetAttr (p, ' name ')) # Iceprint (p.__dict__) # {' Age ': ' Gender ': ' Male ', ' name ': ' Ice ' }print (person.__name__) # personprint (person.__doc__) # Person class print (person.__dict__) # {' __doc__ ': ' Person class ', ' __ weakref__ ': <attribute ' __weakref__ ' of ' person ' objects>, ' __init__ ': <function person.__init__ at 0x000000000284e950>, ' getName ': <function person.getname at 0x000000000284ea60>, ' __dict__ ': <attribute ' _ _dict__ ' of ' person ' objects>, ' __module__ ': ' __main__ '}print (person.__mro__) # (<class ' __main__. Person ', <class ' object ' > ' Print (person.__bases__) # (<Class ' object ',) print (person.__module__) # __main__
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, and that the class method must contain the parameter self, which is the first argument.
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
__P__ in addition to operations
__mod__ Calculating the remainder
__pow__ said Fang
The __init__ () method is a special method, called a constructor or initialization method of a class, that is called when an instance of the class is created, similar to a constructor in C + +. Just rewrite the __init__ () method in your custom class.
Class Person: def __init__ (self, name, age, gender): print (' Enter person initialization ') self.name = name Self.age = Age Self.gender = gender print (' Initialize of person left ') def getName (self): print (self.name) # Person instance Object P = Person (' ice ', 18, ' Man ') print (p.name) print (p.age) print (P.gender) p.getname () # Enter the person's initialization # leave the person's initialization # ice# 18# Man # Ice
destructor __del__, __del__ is called when the object dies, and the __del__ method runs when the object is no longer being used:
Encapsulation of classes
Python distinguishes the access rights of properties and methods by naming them by variable names, which are equivalent to public in C + + and Java
The private property of the class: __private_attrs: Two underscores, declares that the property is private and cannot be used outside of the class or accessed directly. Self.__private_attrs when used in methods inside a class.
Private method of the class: __private_method: Two underscore, declares that the method is a private method and cannot be called outside of a class. Calling Self.__private_methods inside a class
Although Python does not allow instantiated classes to access private data, you can use Object._classname__attrname to access properties. In fact, the implementation of Python's internal privatization only changed the Attrname attribute to _classname__attrname.
Class Demo: __id = 123456 def getId (self): return self.__idtemp = Demo () # Print (temp.__id) # error Attributeerro R: ' Demo ' object has no attribute ' __id ' Print (Temp.getid ()) # 123456print (temp._demo__id) # 123456
Inheritance of Classes
One of the main benefits of object-oriented programming is the reuse of code, and one way to implement this reuse is through inheritance mechanisms. Inheritance can be fully understood as a type and subtype relationship between classes.
What to note: Inherit the syntax class derived class name (base class name)://... The base class name is written in parentheses, and the base class is specified in the tuple at the time the class is defined.
Some of the characteristics of inheritance in Python:
1: The construction of the base class in inheritance (The __init__ () method) is not automatically called, it needs to be called specifically in the construction of its derived class. Use Super (). __init__ () or parentclassname.__init__ ()
2: When calling a method of the base class, you need to prefix the class name of the base class with the Self argument variable. Unlike calling a normal function in a class, you do not need to take the self argument
3:python always looks for a method of the corresponding type first, and if it cannot find the corresponding method in the derived class, it begins to look in the base class one by one. (Find the method that was called in this class before you can find it in the base class).
If more than one class is listed in an inheritance tuple, it is called "Multiple inheritance."
Grammar:
The declarations of derived classes are similar to their parent classes, and the list of inherited base classes follows the class name.
Polymorphic
If the functionality of the parent method does not meet the requirements, you can override the parent class's methods in the subclass. An overridden method that invokes its corresponding subclass when the instance object invokes the method
python3.3 class and inheritance small case
Class Base:def __init__ (self): self.data=[]def Add (self,x): Self.data.append (x) def addtwice (self,x): Self.add (x) Self.add (x) # Child extends BaseClass child (Base):d EF Plus (self,a,b): Return A+bochild=child () ochild.add ("str1") Ochild.add (999) ochild.addtwice (4) print (ochild.data) print (Ochild.plus (2,3))