简体   繁体   English

Python 类中的 self

[英]self in Python classes

I know first argument in Python methods will be an instance of this class.我知道 Python 方法中的第一个参数将是此类的一个实例。 So we need use "self" as first argument in methods.所以我们需要在方法中使用“self”作为第一个参数。 But should we also specify attribures (variables) in method starting with "self."?但是我们是否也应该在以“self.”开头的方法中指定属性(变量)?

My method work even if i don't specify self in his attributes:即使我没有在他的属性中指定 self ,我的方法也能工作:

class Test:
  def y(self, x):
    c = x + 3
    print(c)

t = Test()
t.y(2)
5

and

class Test:
  def y(self, x):
    self.c = x + 3
    print(self.c)

t = Test()
t.y(2)
5

For what i would need specify an attribute in methods like "self.a" instead of just "a"?对于我需要在“self.a”之类的方法中指定一个属性,而不仅仅是“a”?

In which cases first example will not work but second will?在哪些情况下,第一个示例将不起作用,但第二个示例将起作用? Want to see situation which shows really differences between two of them, because now they behave the same from my point of view.想看看显示出他们两个之间真正差异的情况,因为现在从我的角度来看,他们的行为是一样的。

The reason you do self.attribute_name in a class method is to perform computation on that instances attribute as opposed to using a random variable.For Example您在类方法中执行 self.attribute_name 的原因是对该实例属性执行计算,而不是使用随机变量。例如

class Car:
  def __init__(self,size):
      self.size = size

  def can_accomodate(self,number_of_people):
      return self.size> number_of_people

  def change_size(self,new_size):
      self.size=new_size

   #works but bad practice      

   def can_accomodate_v2(self,size,number_of_people):
       return size> number_of_people

 c = Car(5)
 print(c.can_accomodate(2))
 print(c.can_accomodate_v2(4,2))

In the above example you can see that the can_accomodate use's self.size while can_accomodate_v2 passes the size variable which is bad practice.Both will work but the v2 is a bad practice and should not be used.You can pass argument into a class method not related to the instance/class for example "number_of_people" in can_accomodate funtion.在上面的示例中,您可以看到 can_accomodate 使用的 self.size 而 can_accomodate_v2 传递了大小变量,这是不好的做法。两者都可以使用,但 v2 是一种不好的做法,不应使用。您可以将参数传递给类方法而不是与实例/类相关,例如 can_accomodate 功能中的“number_of_people”。 Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM