[英]How can i pass instance attribute in function argument in python
I have this function code 我有这个功能代码
def getList(self, cursor=self.conn_uat.cursor()):
from pprint import pprint
cursor.execute(...)
I am getting this error 我收到了这个错误
NameError: name 'self' is not defined
The reason i am using in args is so that i dont put any dependency inside any function to make testing easier 我在args中使用的原因是我不在任何函数中放置任何依赖项以使测试更容易
self
is only available inside the method getList
. self
仅在 getList
方法中getList
。 However, you are trying to access outside of the method in the function declaration line. 但是,您尝试在函数声明行中访问方法外部。 Hence, you get a NameError
. 因此,您会收到NameError
。
I think the easiest/cleanest solution would be to do this instead: 我认为最简单/最干净的解决方案是:
def getList(self, cursor=None):
from pprint import pprint
cursor = self.conn_uat.cursor() if cursor is None else cursor
cursor.execute(...)
The functionality of the above code is identical to what you were trying to use. 上述代码的功能与您尝试使用的功能相同。
Also, here is a reference on conditional operators if you want it. 此外,如果您需要,还可以参考条件运算符 。
The function is defined in the class declaration, so the specific instance isn't known. 该函数在类声明中定义,因此特定实例未知。 The arguments are created at definition, not at run 参数是在定义时创建的,而不是在运行时创建的
Here's another example of it: "Least Astonishment" and the Mutable Default Argument 这是另一个例子: “最小惊讶”和可变默认参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.