python动态修改类方法和实例方法

您所在的位置:网站首页 修改一个实例不会影响原件也不会影响其他实例 python动态修改类方法和实例方法

python动态修改类方法和实例方法

#python动态修改类方法和实例方法| 来源: 网络整理| 查看: 265

修改类方法

直接将函数绑定到原有的方法上,函数的第一个参数依然是实例self,修改后的方法不仅会作用于新创建的实例,也会作用于修改前创建的实例。

class Student: def __init__(self, name): self.name = name def self_introduce(self): print(f'I am {self.name}.') def new_self_introduce(self): print(f'My name is {self.name}. Nice to meet you!') a = Student('xiaoming') a.self_introduce() Student.self_introduce = new_self_introduce a.self_introduce() b = Student('xiaohong') b.self_introduce()

输出:

I am xiaoming. My name is xiaoming. Nice to meet you! My name is xiaohong. Nice to meet you!

修改实例方法

若采用与上述相同的方式绑定

a.self_introduce = new_self_introduce a.self_introduce()

则会出现错误

Traceback (most recent call last): File “C:/Users/hmy/Documents/git/doc/spiders/hmyspiders/Script/test.py”, line 18, in a.self_introduce() TypeError: new_self_introduce() missing 1 required positional argument: ‘self’

可见实例对象并没有作为参数传入新方法的self中,所以这种方法只能绑定不需要self参数的静态方法。这时可以用types中的MethodType函数来处理,参数为要绑定的新方法,实例,只作用于当前实例

from types import MethodType class Student: def __init__(self, name): self.name = name def self_introduce(self): print(f'I am {self.name}.') def new_self_introduce(self): print(f'My name is {self.name}. Nice to meet you!') a = Student('xiaoming') a.self_introduce() a.self_introduce = MethodType(new_self_introduce, a) a.self_introduce() b = Student('xiaohong') b.self_introduce()

输出:

I am xiaoming. My name is xiaoming. Nice to meet you! I am xiaohong.



【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3