问题描述
正如标题所示,我试图将我的类的一个属性作为同一个类的函数的参数传递.在下面的示例中,print_top_n()
的功能是默认打印 self.topn
,但如果需要,也可以使用不同的值调用该函数.这是 Python(或一般编程)犯规还是有办法做到这一点?
方法是在类创建时创建,方法创建时设置默认值(见这个问题/答案) -- 在调用函数时不会重新计算它们.换句话说,这一切发生在 self
被创建之前很久(因此是 NameError
).
典型的方法是使用可以在 print_top_n
内部检查的标记值(None
是最常见的).
def print_top_n(self, n=None):n = self.topn 如果 n 是 None else n打印 n
As the title indicates, I am trying to pass an attribute of my class as a parameter for a function of that same class. In the example below, the functionality of print_top_n()
would be to print self.topn
by default, but the function could also be called with a different value if need be. Is this a Python (or general programming) foul or is there a way to do this?
>>> 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
The methods are created when the class is created, and the default values are set when the method is created (See this question/answer) -- They aren't re-evaluted when the function is called. In other words, this all happens long before self
has been created (Hence the NameError
).
The typical approach is to use a sentinel value that you can check inside of print_top_n
(None
is the most common).
def print_top_n(self, n=None):
n = self.topn if n is None else n
print n
这篇关于在 Python 中将类属性作为该类的函数的参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!