您的位置:首页 > 其它

动态给类和对象添加属性和方法

2017-10-20 15:09 246 查看

动态给类和对象添加属性和方法

动态给类和对象添加属性

定义一个Person类

class Person(object):
def __init__(self, name):
self.name = name


给对象添加属性

# 创建2个Person,分别为p1,p2

p1 = Person('amy')
print(p1.name)
p1.age = 10         # 给p1对象添加属性
print(p1.age)       # 输出10

p2 = Person('anne')
print(p2.name)
p2.age = 18         # 给p2对象添加属性
print(p2.age)       # 输出18


给类添加属性

Person.sex = 'female'

print(p1.sex)    # 输出 female

print(p2.sex)   # 输出 female

p2.sex = 'male'

print(p2.sex)   # 输出 male


动态给类和对象添加方法

动态给类添加方法

# 在类的外部定义一个sleep函数

def sleep(self):
print('%s sleep' % (self.name))

Person.sleep = sleep

Person.sleep(p1)     # 输出 amy sleep

Person.sleep(p2)     # 输出 anne sleep


给对象添加方法

import types    # 如果是给对象动态添加方法,需要导入types模块

def eat(self):
print('%s eat' % (self.name))

p.eat = types.MethodType(eat, p)    # 调用MethodType()函数,参数1:方法名,参数2:对象名

p.eat()             # 输出 amy eat
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: