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'