#运行中给对象添加属性和方法
import types #添加方法的库
class Animal(object):
def __init__(self,name,age):
self.name=name
self.age=age
pass
pass
cat=Animal('小猫',2)
print(cat.age)
cat.color='黄色' #动态绑定color的属性
print(cat.color)
print('--------------------------')
dog=Animal('小狗',3)
# print(dog.color) #小狗不具备color的属性
#给类添加属性
class Animal(object):
def __init__(self,name,age):
self.name=name
self.age=age
pass
pass
Animal.foot=4 #动态给类添加属性
cat=Animal('小猫',5)
print(cat.name)
print(cat.foot)
print('------------------')
tiger=Animal('老虎',3)
print(tiger.foot) #同样具备foot的属性
print('----------------------------------')
#给类办法定类方法和静态方法 语法:类名.方法名=XXXX
@classmethod #定义一个类方法
def eat(cls):
print('吃东西')
pass
@staticmethod #定义一个静态方法
def drink():
print('喝水')
pass
Animal.eat=eat #给Animal类绑定方法
Animal.eat()
Animal.drink=drink #给Animal绑定静态方法
Animal.drink() #调用静态方法
运行结果