[英]Usage of self inside instance methods in Python
I have a class like this 我有这样的课
class Test:
def __init__(self, var):
self.var = var
def test(self):
x = self.var + 2
return x
And then I make a class like this 然后我上这样的课
class Test:
def __init__(self, var):
self.var = var
def test(self):
self.x = self.var + 2
return self.x
I understand that I can use self
to separate attribute values across various instances of this class. 我知道我可以使用self
来分隔此类的各种实例中的属性值。 My question is, if I create many utility variables (like x
) inside a method, should I always create them using self
? 我的问题是,如果我在一个方法中创建许多实用程序变量(如x
),是否应该始终使用self
创建它们?
Can anyone explain how the above two classes behave differently (if they do)? 谁能解释上述两个类的行为方式不同(如果有)?
Let's see the difference between the two classes : 让我们看看两个类之间的区别:
class Test:
def __init__(self, var):
self.var = var
def test(self):
x = self.var + 2
return x
Let's create a Test object: 让我们创建一个Test对象:
t = Test(1)
And see what we can do 看看我们能做什么
t.var # 1
t.x # Raises AttributeError : no such attribute in the class
t.test() #3
t.x # Still erroring
And with your second class 第二节课
class Test:
def __init__(self, var):
self.var = var
def test(self):
self.x = self.var + 2
return self.x
Let's create a Test object: 让我们创建一个Test对象:
t = Test(1)
And see what we can do 看看我们能做什么
t.var # 1
t.x # Raises AttributeError : no such attribute in the class
t.test() #3
t.x # 3
So what ? 所以呢 ? Well we can see that any variables defined with self.VARNAME
persist in the instance, while simple local variables, without self.
好了,我们可以看到任何用self.VARNAME
定义的变量self.VARNAME
保留在实例中,而简单的局部变量则没有self.
, dosen't. ,没有。
However, if x needs to be accessible with tx, i'd probably go for a property, like so 但是,如果x需要通过tx进行访问,我可能会选择一个属性,就像这样
class Test:
def __init__(self, var):
self.var = var
@property
def x(self):
x = self.var + 2
return x
t = Test()
t.x # 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.