gpt4 book ai didi

python - 将方法分配给变量时缺少 1 个必需的位置参数 :'self'

转载 作者:行者123 更新时间:2023-12-01 03:56:56 25 4
gpt4 key购买 nike

我试图将方法的返回值分配给变量,但遇到了此错误。

class MyClass():

def my_def(self):
return "Hello"

my_variable = my_def()

这是我想做的 Java 等效项。

public class NewException {
public int method1(){

return 1;
}
public int variable = method1();
}

我确信这很简单,但我什至找不到合适的词来谷歌搜索。如有任何帮助,我们将不胜感激。

最佳答案

让我们从方法和函数之间的区别开始,基本上方法属于某个对象,而函数则不属于。例如

def myFunction():
return "F"

class MyClass:
value = 0
def myMethod(self, value):
old = self.value
self.value = value
return old

myClassInstance = MyClass()
print myClassInstance.myMethod(3)
# 0
print myClassInstance.myMethod(33)
# 3
print myFunction()
# F

请注意,该方法绑定(bind)到实例,在创建实例之前调用该方法是没有意义的。考虑到这一点,你的错误应该更有意义。如果没有实例(self),则无法调用该方法。这不是唯一的方法,例如还有“静态方法”。静态方法在类上定义,但在没有实例的情况下调用它们。例如:

class MyClass:
@staticmethod
def myStaticMethod():
return "static method"
# Consider using an instance attribute instead of a class attribute
def __init__(self):
self.instance_attribute = MyClass.myStaticMethod()
# Or if you need a class attribute it needs to go outside the class block
MyClass.class_attribute = MyClass.myStaticMethod()

关于python - 将方法分配给变量时缺少 1 个必需的位置参数 :'self',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37289391/

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