How Python dynamically add a method or property of an object, __ slots__ usage

Code examples are as follows:

import types # use MethodType method requires introduction package

class test (object): # define a test class, comprising a name attribute and f () method

def __init__(self, name):

self.name = name

def f(self):

print("test")

#__slots__ = ( 'name') # phrase fixing the test properties of an object class is only name ,

# Is not allowed to have other properties

def test2 (self): # define a function, ready to add to the test object class

print("name:%s"%self.name)

a = test ( " Wang ")

a.f()

 

a.age = 18 # moving as a target attribute is added, if the setting __slots__ property, these words being given

print ( ' Age: % D' a.age%)

 

a.test2 = types.MethodType (test2, a) # dynamically add method, test2 bound method to a on the object

a.test2 ()

Guess you like

Origin www.cnblogs.com/sy-zxr/p/12054060.html