Skip to main content
 首页 » 编程设计

python之在 Python 中将类属性作为该类函数的参数传递

2025年05月04日16leader

如标题所示,我试图将我的类的一个属性作为同一类函数的参数传递。在下面的示例中,print_top_n() 的功能是默认打印 self.topn,但如果需要,也可以使用不同的值调用该函数。这是 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 

请您参考如下方法:

方法在创建类时创建,默认值在创建方法时设置(参见 question/answer)——调用函数时不会重新计算它们。换句话说,这一切都发生在 self 被创建之前很久(因此 NameError)。

典型的方法是使用一个标记值,您可以在 print_top_n 中检查它(None 是最常见的)。

def print_top_n(self, n=None): 
    n = self.topn if n is None else n 
    print n