正如標題所示,我試圖傳遞我的類的屬性作爲該類的一個函數的參數。在下面的示例中,默認情況下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