class m2:
x, y = 4, 5 #This are class attributes
def add(self, x, y):
return self.x + self.y # This are instance variables
def add2(self, x, y):
return x + y # This are local variables
类变量对于类的每个实例都是通用的。实例变量仅适用于该实例。局部变量仅在函数的范围内可用。
在add
,当你做self.x
它是指类变量x
因为它也是实例的一部分。在add2
它指的局部变量
相同的结果可以实现,如果这些方法是class methods or static methods(通过适当调整)
类方法:
class m2:
x, y = 4, 5
@classmethod
def add(cls, x, y):
return cls.c + cls.y #Here you're calling class attributes
@classmethod
def add2(cls, x, y):
return x + y
结果:
>>> m.add(1,2)
9
>>> m.add2(1,2)
3
静态方法:
class m2:
x, y = 4, 5
@staticmethod
def add(x, y):
return m2.c + m2.y #Here you need to call the class attributes through the class name
@staticmethod
def add2(x, y):
return x + y
结果:
>>> m2.add(1,2)
9
>>> m2.add2(1,2)
3
的可能的复制[Python中:类和实例之间的区别属性(http://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-属性) – idjaw
@idjaw我不认为这是你链接问题的重复。在这个问题中没有一个实例属性,所以它不是混淆类和实例属性。 –
在第一个'add'中,您添加了'self'对象的属性值。在第二个'add2'中,您正在添加参数的值。 –