python语言的动态性主要体现在:
**可是给实例添加属性
**可以给实例添加方法
**可以给类添加属性
**可以给类添加类方法或者静态方法
先定义一个简单的测试类
class Person(object):
def __init__(self,name,age):
self.name=name
self.age=age
print("name:" + name + " age:" + str(age))
1.给实例添加属性
p1 = Person('小红',100)
p1.phone = '178212122121'#给对象添加属性
print(p1.phone)
2.给实例添加方法
#动态添加方法给对象
def info(self):
print('---this is out from info function----')
print('name:'+self.name.upper() + '######')
print('---end of info function----')
#通过types.MethodType(funcName,instance)将info方法动态的添加给对象p1
import types
p1.info = types.MethodType(info,p1)
p1.info()
#注意,这样也是正确可执行的
newName = types.MethodType(info,p1)
newName()
3.给类添加属性
Person.country='china' #给类添加属性
p2=Person('小明',99)
print(p2.country)
#print(p2.phone) #这一行会报错,因为phone属性只添加给了对象p1。
#p2.country 不会报错,是以为country属性添加给了类Person,所有Person类的实例共享。
4.给类添加静态方法和类方法
#给类添加静态方法
@staticmethod
def staticFunc(name):
print('我是一个静态方法:'+name)
Person.staticF=staticFunc
Person.staticF("hello")
#给类添加类方法
@classmethod
def funcMethod(cls,test):
print('我是一个类方法:' + test)
Person.funcM = funcMethod
Person.funcM("HAHA")
5.__slots__限制给对象添加属性的范围,但是不限制给类添加属性。
class Person(object):
__slots__=('name','phone')
def __init__(self):
print('--Person--init---')
p1 = Person()
p1.name='haha'
p1.phone='1782123213'
Person.country='china' #给类添加__slots__之外的属性是可以的
print('----'+p1.country+'****')
print('---分割线--')
p1.age=12 #这一行会报错,'Person' object has no attribute 'age'
Person.country='china'