简体   繁体   English

我如何在python中的函数参数中传递实例属性

[英]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.

相关问题 如何在python中的函数中传递对象的实例作为参数? - How do I pass instance of an object as an argument in a function in python? 如何将实例绑定描述符作为参考参数传递给 function? - How can I pass an instance binding descriptor as a reference argument to a function? 如何在Python中传递函数乘以常数作为参数 - How can I pass a function multiplied by a constant as argument in Python python - 如何在python pandas管道中将函数作为参数传递给参数 - How can I pass function as argument with parameter in python pandas pipe 我可以将异常作为参数传递给python中的函数吗? - Can I pass an exception as an argument to a function in python? 如何创建一个 function 调用另一个 function 并将实例属性作为参数传递? - How can I create a function that calls another function and passes in an instance attribute as an argument? 如何将 function 参数作为 python 中的模块属性传递? - How can I pass a function parameter as an attribute of a module in python? Python将自身的实例作为另一个函数的参数传递 - Python pass instance of itself as an argument to another function Python-将实例函数调用传递给属性 - Python - Pass instance function calls to attribute 如何将位置参数传递给 python 函数中的可选参数? - How can I pass a positional argument to an optional argument in python functions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM