使用属性作为相同方法的参数 class

Using an attribute as argument of a method of the same class

我想定义一个 class 的属性,然后按以下方式在同一个 class 中将其用作方法的参数

class Class1:
    def __init__(self,attr):
        self.attr=attr
    def method1(self,x=self.attr):
        return 2*x


它returns一个错误:NameError: name 'self' is not defined

我如何定义该方法,以便在我不显式编写 x 时它只使用属性 attr

在例子中,我的意思是我想要

cl=Class1()
print cl.method1(12) # returns '24'
cl.attr= -2
print cl.method1() # returns '-4'

在您的代码中,您似乎将 x 命名为传递给函数的参数,而实际上您正在为 init 函数提供值,请尝试以下代码:

class Class1:
    def __init__(self,attr = 3):
        self.attr=attr
    def method1(self):
        y = (self.attr)*(2)
        return y

当你调用函数时,你应该这样做:

result = Class1(4)
print(result.method1())

>>8

P.T。我是 Python 的新人,所以不要理所当然地给出我的答案,或者好像这是解决您问题的最佳方法。

这是因为在 method1 中,您只是在第一个参数中定义了 self 变量。并且 self 变量只能在函数体中使用。 您可能认为 self 是一个特殊的关键字。实际上 self 只是一个普通变量,就像其他任何变量一样。

解决问题: 在函数定义中使用默认值并在函数体中检查它:

class Class1:
    def __init__(self):
        self.attr = 3

    def method1(self, x=None):
        x = self.attr if x is None else x
        return 2*x


cl = Class1()
print(cl.method1(12))
cl.attr=-2
print(cl.method1())

结果:

24
-4