正如标题所示,我试图传递我的类的属性作为该类的一个函数的参数。在下面的示例中,默认情况下print_top_n()
的功能将打印self.topn
,但如果需要,也可以使用不同的值调用函数。这是一个Python(或一般编程)犯规还是有办法做到这一点?将类属性作为Python中该类的函数的参数传递
>>> class Example():
def __init__(self, topn=5):
self.topn = topn
def print_top_n(self, n=self.topn):
print n
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
class Example():
File "<pyshell#7>", line 4, in Example
def print_top_n(self, n=self.topn):
NameError: name 'self' is not defined