繁体   English   中英

将类属性作为该类函数的参数传递给Python

[英]Pass class attribute as parameter of a function of that class in Python

如标题所示,我试图将类的属性作为该类的函数的参数传递。 在下面的示例中, 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

一种选择是使用标记对象。 这是比n=None (取决于您的api的实际意图)更好的模式,因为即使有人故意通过n=None它也可以工作。

marker = object()

class Example:
    def __init__(self, topn=5):
        self.topn = topn

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

方法是在创建类时创建的,而默认值是在创建方法时设置的(请参阅此问题/答案 )-调用函数时不会重新评估它们。 换句话说,这一切发生在创建self之前很久(因此NameError )。

典型的方法是使用可以在print_top_n内部检查的哨兵值(最常见的是None )。

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

没有; 被定义的功能时的缺省值被评估,所以没有对象尚未执行的一个属性的访问。 您可以使用前哨值:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM