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'中,您正在添加參數的值。 –