python 中给class动态绑定属性和方法
- 给实例绑定属性:
可以这样写:
In [22]: class Hello(object):
...: def say(self,str='world'):
...: print('hello:'+str)
...:
In [23]: Hi=Hello()
In [24]: Hi.say('wangorg')
hello:wangorg
In [25]: Hi.name='wangorg'
In [26]: Hi.name
Out[26]: 'wangorg'
- 但是给实例绑定方法的时候:
In [29]: def SAY(strs=''):
...: print('emmmmm....'+strs)
...:
In [30]: Hi.SAY=SAY
In [31]: Hi.SAY()
emmmmm....
In [32]: def HaHa(self):
...: print('hahaha')
...:
In [33]: Hi.haha=HaHa
In [34]: Hi.haha()
Traceback (most recent call last):
File "<ipython-input-34-7c169b9f9daa>", line 1, in <module>
Hi.haha()
TypeError: HaHa() missing 1 required positional argument: 'self'
In [35]: Hi.haha(Hi)
hahaha
也就是说 ,给实例动态绑定方法的时候,可以不用加self参数
- 给对象绑定属性和方法:
可以这样写:
In [45]: def say1():
...: print('say1')
...:
In [46]: Hello.say1=say1
In [47]: Hello.say1()
say1
In [52]: Hello.haha=HaHa
In [54]: z=Hello()
In [55]: z.haha()
hahaha
In [56]: z.say1()
Traceback (most recent call last):
File "<ipython-input-56-01536cc86bee>", line 1, in <module>
z.say1()
TypeError: say1() takes 0 positional arguments but 1 was given
In [57]: z.SAY()
Traceback (most recent call last):
File "<ipython-input-57-edd8f061827c>", line 1, in <module>
z.SAY()
File "<ipython-input-29-2541ec6da779>", line 2, in SAY
print('emmmmm....'+strs)
TypeError: must be str, not Hello
In [58]: Hello.haha()
Traceback (most recent call last):
File "<ipython-input-58-27e23b6ea8da>", line 1, in <module>
Hello.haha()
TypeError: HaHa() missing 1 required positional argument: 'self'
In [59]: Hello.haha(Hello)
hahaha
也就是说,给对象绑定的方法,如果给实例用的话,需要一个self
如果是对象用的话,有和没有都可以,只是有self
的时候,需要手动传入一个参数
__slots__
的使用
__slots__
是为了限定给实例动态绑定方法的
In [1]: class Person(object):
...: __slots__=('name','age','eat')
...:
...:
In [2]: XX=Person()
In [3]: XX.name='xiaoxiao'
In [4]: XX.age=19
In [5]: XX.grade=98
Traceback (most recent call last):
File "<ipython-input-5-cd4b1976feca>", line 1, in <module>
XX.grade=98
AttributeError: 'Person' object has no attribute 'grade'
In [6]: setattr(XX,'grade',98)
Traceback (most recent call last):
File "<ipython-input-6-e5a948bf8f0e>", line 1, in <module>
setattr(XX,'grade',98)
AttributeError: 'Person' object has no attribute 'grade'
- 但是,如果这么写:
In [1]: class Person(object):
...: pass
...:
In [2]: Person.__slots__=('name','age','eat')
In [3]: XX=Person()
In [4]: XX.name='xiaoxiao'
In [5]: XX.grade=98
In [6]: Person.gt='gt'
In [7]: XX.grade
Out[7]: 98
In [8]: XX.gt
Out[8]: 'gt'
也就是说,动态的给class
绑定__slots__
属性,并不起作用
* 更好的讲解请看廖大神的python教程*