【发布时间】:2019-08-28 10:20:45
【问题描述】:
我遇到了一些问题。我们如何在可以在类属性中使用的函数之外定义一个函数?另外,我们如何将self 参数插入到函数签名中?我想把它想象成这样:
>>> def a(self, x): #I thought maybe class will give "self" to this property function
... print(self)
...
>>> class aa:
... def __init__(self):
... pass
... @a
... def p():
... print('in it')
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in aa
TypeError: a() missing 1 required positional argument: 'x'
我想在外部定义一个函数,但在类内部使用。就像一个类的方法作为一个属性。我该怎么做?
【问题讨论】:
-
我不确定我是否理解您的要求。每当
aa实例的某些属性被访问时,您是否要实际使用property调用a函数?或者你只是使用property作为装饰器的一个例子,它经常与@property一起应用?因为你可以做这些事情中的任何一个,如果你明白你想要什么。您也可以将定义在类之外的函数复制到类中,并将其用作常规方法(不涉及装饰器或属性)! -
第一个。我要获取类的属性
标签: python python-3.x abc