# 例子一
# 导入MethodType模块
from types import MethodType
# 定义空类
class ExampleA(object):
pass
# 空类实例化
examA = ExampleA()
# 定义添加的函数
def funcExam(self, age):
self.age = age
# 添加函数
examA.funcExam = MethodType(funcExam, examA)
# 使用定义的函数
examA.funcExam(25)
# 使用定义的函数带的属性
print(examA.age)
# 例子二
# 使用另一个实例进行测试
examB = ExampleA()
# examB.funcExam(25) # 没有该属性
# examB.age报错, 没有该属性
# examB.age
# 例子三
# 添加属性或方法到类,而不是类的实例
ExampleA.funcExam = MethodType(funcExam, ExampleA)
# 添加类方法
ExampleA.funcExam(100)
print(ExampleA.age)
examC = ExampleA()
#examC.funcExam(50)
print(examC.age)
# 添加类属性
ExampleA.name = "Oliver"
examD = ExampleA()
print(examD.name)
# 定义添加的函数, 不能把方法当成属性,直接添加如类中, 但可以通过MethodType方法来添加
# 至于属性, 类名.属性名 = 值, 这种方式就可以添加类属性
def funcExamB(self, phone):
self.phone = phone
ExampleA.funcExamB = MethodType(funcExamB, ExampleA)
ExampleA.funcExamB(137)
exambfuncInstance = ExampleA()
print(exambfuncInstance.phone)
Python3 类属性方法外部添加
最新推荐文章于 2022-01-10 21:09:13 发布