gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:59 26 4
gpt4 key购买 nike

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

关于python - 在 Python 中将类属性作为该类函数的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41811832/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com