总结:
可以将一个方法以属性的方式调用,但是该方法有且只能有一个self参数,要不然参数传不进去。设置的时候也只有一个参数(设置多个值时会自动组包成一个元组)!
property属性示例:
In [9]: class A():
...: def __init__(self):
...: self.x =2
...: self.y =8
...: @property
...: def a(self):
...: return self.x+self.y
...: @a.setter
...: def a(self,y):
...: self.y=y
...: print("in setter y")
...: @a.deleter
...: def a(self):
...: print("in deleter")
In [10]: w = A()
In [11]: w.a
Out[11]: 10
In [12]: w.a=88
in setter y
In [13]: w.a
Out[13]: 90
In [14]: w.a = 98
in setter y
In [15]: w.a
Out[15]: 100
In [16]: del w.a
in deleter
传参的情况:
In [33]: w.a(10) # 报错相当于调返回值
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-33-4acca0ceb81b> in <module>()
----> 1 w.a(10)
TypeError: 'int' object is not callable
设置值的时候传多个:
In [17]: w.a=10,20
out [18]: in setter y
# 再调用时报错,因为设置值的时候会将多个值自动组包成一个元组!!!
In [18]: w.a
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-18-4a0c357bc893> in <module>()
----> 1 w.a
<ipython-input-9-65459ed536ec> in a(self)
5 @property
6 def a(self):
----> 7 return self.x+self.y
8 @a.setter
9 def a(self,y):
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
示例:
定义一个变量设置多个值时也会自动组包成一个元组:
In [29]: uu = (10,20),(30,40)
In [30]: uu
Out[30]: ((10, 20), (30, 40))
In [29]: uu =10,"aa",80
In [30]: uu
Out[30]: (10,"aa",80)