class Person(object):
name = "xiaoMing"
def __init__(self):
self.name = "hhh"
self.age = "hehehe"
def show(self):
print("My name is %s,age is %s,height is %d" % (self.name, self.age, self.height))
xiaoMing = Person()
# 原来没有实例变量self。height,我们根据程序需要动态添加这个变量
# xiaoMing.height = 180
Person.height = 180
xiaoMing.show()
# del Person.height
xiaoHong = Person()
xiaoHong.show()
# help(Person)
"""
> **总结:**<br/>
运行中给对象绑定属性-----》直接通过实例对象设置<br/>
运行中给类绑定属性-----》直接通过类对象设置<br/>
"""
def run(self):
print("正常人跑步的速度可以在10公里每小时,短距离可以达到36公里每小时")
# 使用实例对象直接添加方法-----》失败
# xiaoHong.run = run
# xiaoHong.run()
# help(xiaoHong)
# 使用类对象添加普通方法----》成功
Person.run = run
xiaoHong.run()
# help(Person)
# 使用类对象添加静态方法----》成功
@staticmethod
def study():
print("I love Study:Study is a beauty")
Person.study = study
# help(Person)
# 使用类对象添加类方法----》成功
@classmethod
def play_game(cls):
print("wo xi huan wan you xi")
Person.play_game = play_game
help(Person)
# 使用type,继承原来的类,同时再添加方法
def sleep(self):
print("我每天睡眠时间大概6个小时")
Person = type("Person", (Person,), {"sleep": sleep})
help(Person)
# 创建对象,使用的是离得近的Person
xiaoHua = Person()
# 自己的sleep方法
xiaoHua.sleep()
# 父类的show方法
xiaoHua.show()
import types
# 动态删除自己的方法---》成功
del Person.sleep
# xiaoHua.sleep()
print("*" * 30)
# 动态删除父类的方法 -->失败
# del Person.show
print("*" * 30)
help(Person)
class Cat:
def __init__(self):
self.name = "Tom"
self.age = 3
def show(self):
print("name:%s,age:%d" % (self.name, self.age))
tom = Cat()
tom.show()
def catch_mouse(self):
print("猫捉老鼠")
# 使用types完成上节课未完成的事业
tom.catch_mouse = types.MethodType(catch_mouse, tom)
tom.catch_mouse()