Python 3-5 动态绑定属性和方法

python 动态绑定属性和方法

Python 是动态语言,在类定义了之后,还可以动态地绑定属性和方法。

# 类对象和实例对象的属性以及动态添加的属性:__dict__
from types import FunctionType,MethodType

class A:
    x=1
    def __init__(self,m,n):
        self.m=m
        self.n=n

    def foo(self):
        pass

def f(self,name):
    self.name=name

def g(self,age):
    self.age=age


A.g=g                   # function g 属于A
a=A('M','N')            # m='M' n='N'
a.g(1)                  # age=1
print(a.g)              # bound method g of a  
a.f=MethodType(f,a)     # bound method f of a  仅当a
print(a.f('demo'))      # name='demo'

print(a.__dict__) # 当前实例对象所有可写的属性 writable
# {'m': 'M', 'n'

猜你喜欢

转载自blog.csdn.net/weixin_43955170/article/details/113105601