Python Decorator
Naming a property starting with a single underscore implies that the property is protected and is not recommended for direct access, so if you want to access the property, you can do so using the getter and setter methods of the property. To do this, consider using the @property wrapper to wrap getter and setter methods to make access to properties secure and convenient, as shown below.
1 | class Person(object): |
__slots__
for dynamic binding
Python is a dynamic language. In general, dynamic languages allow us to bind new properties or methods to an object while the program is running, as well as unbind already bound properties and methods. However, if we need to qualify an object of a custom type to bind only certain properties, we can qualify it by defining a variable called __slots__
in the class. It is important to note that the limitation of __slots__
only applies to the object of the current class and does not apply to subclasses. The example presents above.
Static method
Static method belongs to class rather than objects. The example presents above. @staticmethod
Class method
Python class methods defined in the class, class method called the first parameter named “cls”, it represents the current class related information of the object (the class itself is an object, some places also called metadata object of a class), we can get through this parameters and related information and can create the object of the class, the code is shown above. @classmethod
Poly-Morphism
A subclass that inherits a parent class’s methods can give a new implementation version of the parent class’s existing methods, an action called method override. By method override we can make the same behavior of the parent class have different versions of the implementation in the subclass, and when we call this subclass override method, the different subclass objects behave differently, and this is polymorphic.
1 | from abc import ABCMeta, abstractmethod |
In the above code, we treated the Pet class as an abstract class. An abstract class is a class that cannot create an object, but exists only to allow other classes to inherit it. Python doesn’t support abstract classes syntactically like Java or C# does, but you can use the ABCMeta
meta-class of the ABC module and the abstractmethod
wrapper to achieve the effect of abstract classes. If an abstractmethod exists in a class, the class cannot be instantiated (creating objects). In the code above, the Dog and Cat subclasses rewrite the make_voice abstract method in the Pet class and give different versions of the implementation, and when we call the method in the main function, the method behaves polymorphic (the same method does different things).
The content of this blog is concluded from Jackfrued’s GitHub. Thank you.