将类变量作为默认值分配给类方法参数 [英] assigning class variable as default value to class method argument
问题描述
我想在一个类中构建一个方法,并使用从这个类中获取的默认值参数.一般来说,我会过滤一些数据.在我的课程中,我有一个方法,通常我传递数据向量.有时我没有向量,而是使用模拟数据.每次我不传递特定向量时,我都希望默认采用模拟数据.我认为这应该是一个简单的构造,在我的方法定义中我说 a=self.vector
.但由于某种原因,我有一个错误 NameError: name 'self' is not defined
.简化的构造是:
I would like to build a method inside a class with default values arguments taken from this class. In general I do filtering on some data. Inside my class I have a method where normally I pass vector of data. Sometimes I don't have the vector and I take simulated data. Every time I do not pass a particular vector I would like to take simulated data by default. I thought it should be an easy construction where inside my method definition I say a=self.vector
. But for some reason I have an error NameError: name 'self' is not defined
. The simplified construction is:
class baseClass(object): # This class takes an initial data or simulation
def __init__(self):
self.x = 1
self.y = 2
class extendedClass(baseClass): # This class does some filtering
def __init__(self):
baseClass.__init__(self)
self.z = 5
def doSomething(self, a=self.z):
self.z = 3
self.b = a
if __name__ == '__main__':
a = extendedClass()
print a.__dict__
a.doSomething()
print a.__dict__
我期望的输出应该是:
{'y': 2, 'x': 1, 'z': 5}
{'y': 2, 'x': 1, 'z': 3, 'b': 5}
我尝试了默认赋值为 def doSomething(self, a=z):
显然它永远不会工作.据我了解 self.z
在此范围内可见,将其作为默认值应该没有问题.不知道为什么我有这个错误以及如何做.这可能是一个简单的问题,但我已经尝试弄清楚或找到不缺乏的解决方案.我发现 类似 问题仅针对其他语言.
I tried default assignment as def doSomething(self, a=z):
obviously it doesn't work ever. As far as I understand self.z
is visible in this scope and should not be a problem to have it as a default value. Don't know why I have this error and how to do it. This is probably an easy question, but I try to figure it out or find the solution with no lack for sometime already. I found similar questions only for other languages.
推荐答案
你的理解有误.self
本身就是该函数定义的一个参数,因此它不可能在此时的作用域内.它只在函数本身的范围内.
Your understanding is wrong. self
is itself a parameter to that function definition, so there's no way it can be in scope at that point. It's only in scope within the function itself.
答案只是将参数默认为None
,然后在方法内部检查:
The answer is simply to default the argument to None
, and then check for that inside the method:
def doSomething(self, a=None):
if a is None:
a = self.z
self.z = 3
self.b = a
这篇关于将类变量作为默认值分配给类方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!