python dynamic binding properties and methods

  Tested based on Python 2.7.13.

  

  Python is a dynamic language. After the class is defined, properties and methods can be dynamically bound.

  Let's first look at how to dynamically bind properties and methods to an instance of a class.

>>> class Student(object):
...     pass
...
>>> stu1 = Student();
>>> stu1.name = 'Tom'
>>> print(stu1.name)
Tom
>>> print(dir(stu1))
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__', 'name']
>>>
>>> def set_age(self, age):
...     self.age = age
...
>>> set_age(stu1, 20)
>>> print(stu1.age)
20
>>> print(dir(stu1))
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__ ' , ' age ' , ' name ' ] 
>>> #The method is not bound to the instance 
...
 >>> from types import MethodType
 >>> stu1.set_age = MethodType(set_age, stu1)
 >>> stu1 .set_age(33 )
 >>> print (stu1.age)
 33
>>> print(dir(stu1))
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__ ' , ' age ' , ' name ' , ' set_age ' ] 
>>> #Binding attributes and methods only belong to stu1, not for other instances 
...
 >>> stu2 = Student()
 >>> print (dir(stu2))
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__']

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325383736&siteId=291194637