Reference tutorial:
Python object-oriented promotion and sending and receiving mail 04
Python object-oriented promotion and sending and receiving mail 05
Python object oriented promotion and email 06
Dynamically add properties and methods to instances
- It embodies the characteristics of dynamic language (flexible)
- Attributes and methods added to one object have no effect on other objects
- Add attributes dynamically
- for example
class Person(object): # Create class pass per = Person() # Instantiate object # Add attributes dynamically per.name = "Tom" print(per.name) The result is: Tom
- Dynamic addition method
- The MethodType in the types module needs to be imported
from types import MethodType class Person(object): # Create class pass per = Person() # Instantiate object # Dynamic addition method def say(self): # Method to add print("my name is", self.name) per.speak = MethodType(say, per) # Equivalent to partial function per.speak() # Execute the speak() function The result is: my name is Tom
- Think: what if we want to limit the properties or methods that the instance dynamically adds? For example, only name, age, height, weight attributes and speak methods are allowed to be added to objects
Solution: when defining a class, define a special attribute__ slots__, You can restrict dynamically added properties or methods. An error will be reported if an attribute or method outside the limit is added dynamically
For example:
from types import MethodType class Person(object): # Create class __slots__ = ("name", "speak") # Only name and speak can be added dynamically per = Person() # Instantiate object # Add attributes dynamically per.name = "Tom" print(per.name) # Dynamic addition method def say(self): # Method to add print("my name is", self.name) per.speak = MethodType(say, per) # Equivalent to partial function per.speak() # Execute the speak() function result: Tom my name is Tom
Private property
It starts with two underscores and declares that the property is private and cannot be used or accessed directly outside the class. When used in methods inside a class, self__ Attribute name
Attributes are directly exposed to the outside world, unsafe, and there is no data filtering. The solution is to restrict its access, that is, private attributes
To access private properties, you need to write your own get and set methods
For example:
- Method 1
Using get and set methods
class Person(object): def __init__(self, age): self.__age = age # Private property def getAge(self): # Take out__ Value of age return self.__age # Return__ Value of age def setAge(self, age): # Filter data for__ age assignment if age < 0: # Filter data age = 0 self.__age = age # For__ age assignment per = Person(18) # Instantiate object per.setAge(28) # assignment print(per.getAge()) # Call the getAge() method and print the result result: 28
- Method 2
Use @ property function as decorator
class Person(object): def __init__(self, age): self.__age = age # Private property @property # The property function is used as a decorator to easily create read-only properties # Remove the double underscore from the restricted variable of the method name def age(self): # Take out__ The value of age is equivalent to calling getAge return self.__age # Return__ Value of age @age.setter # Remove the double underline Setter, the setter method of property can also be used as a decorator # Remove the double underscore from the restricted variable of the method name def age(self, age): # Filter data for__ The assignment of age is equivalent to calling setAge. It cannot be placed before the age(self) function, otherwise an error will be reported if age < 0: # Filter data age = 0 self.__age = age # For__ age assignment per = Person(18) # Instantiate object per.age = 28 # This is equivalent to calling setAge print(per.age) # Equivalent to calling getAge result: 28
operator overloading
Class specific methods can be overloaded
Class specific methods:
__ init__ : Constructor, called when the object is generated
__ del__ : Destructor, used when releasing an object
__ repr__ : Printing, converting
__ setitem__ : Assignment by index
__ getitem__: Get value by index
__ len__: Get length
__ cmp__: The comparison operation has been disabled in python3, but it is available in python2
Refer to: Operator - standard operator substitution function
__ call__: function call
__ add__: Addition operation
__ sub__: Subtraction operation
__ mul__: Multiplication operation
__ truediv__: Division operation
__ mod__: Remainder operation
__ pow__: Power method
...
Overloaded operator: it refers to defining and implementing a processing method corresponding to the operator in the class, so that when the class object is operating the operator, the system will call the corresponding method in the class for processing.
Common overloaded operators:
reference resources:
Analysis of Python operator overloading
Also refer to:
What are operator overloading and what are Python overloadable operators?
Operator overloading of classes in Python
example:
class Person(object): def __init__(self, num, name): self.num = num self.name = name def __add__(self, other): return self.num + other.num def __str__(self): return "num = %d" % (self.num) # return "num = " + str(self.num) def __len__(self): print("The string length is:", end="") return len(self.name) per1 = Person(1, "Tom") per2 = Person(2, "Jerry") print(per1 + per2) # Call__ add__, Equivalent to print (Per1. _add_ (per2)) print(per1) # Call__ str__, Equivalent to print (Per1. _str_) print(per2) # Call__ str__, Equivalent to print (per2. _str_) print(len(per1)) # Call__ len__, Equivalent to print (Per1.) result: 3 num = 1 num = 2 String length: 3