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

修改类方法

直接将函数绑定到原有的方法上,函数的第一个参数依然是实例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 <module>
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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值