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