python中对象添加删除实例变量、方法(对象的动态性)

class Person:
		def __init__(self,name,age):
				self.name=name
				self.age=age
		def  say(self,content):
				print(content)

类Person中只有name,age变量和say方法

对象添加实例变量

me=Person('me',10)
me.skill='eat'
print(me.skill)
print('--------------------')
you=Person('you',8)
print(you.skill)

输出如下:

eat
--------------------
Traceback (most recent call last):
  File "test.py", line 12, in <module>
    print(you.skill)
AttributeError: 'Person' object has no attribute 'skill'

所以只对该实例对象(me)添加额外的实例变量,没有为该类的其余对象(例如you)添加

删除实例变量

del me.skill
print(me.skill)

输出如下:

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    print(me.skill)
AttributeError: 'Person' object has no attribute 'skill'

对象添加方法

me=Person('me',10)
def run(x):
	print("-----run-----",x)
me.newfunc=run
me.newfunc(me)
print('*'*10)
me.newfunc()

给me这个对象添加了newfunc方法,输出如下:

-----run----- <__main__.Person object at 0x7f13b86d8a90>
**********
Traceback (most recent call last):
  File "test.py", line 13, in <module>
    me.newfunc()
TypeError: run() missing 1 required positional argument: 'x'

与类中本来就定义的方法不同,调用时需要传入参数。这是因为类中方法自动将该对象绑定为第一个参数self,而添加的方法则不会。
可通过types模块的MethodType进行包装:

me=Person('me',10)
def run(x):
	print("-----run-----",x)
from types import MethodType
me.newfunc=MethodType(run,me)
me.newfunc()
print('*'*10)
me.newfunc(me)

输出如下:

-----run----- <__main__.Person object at 0x7f957fb8da90>
**********
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    me.newfunc(me)
TypeError: run() takes 1 positional argument but 2 were given
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值