Python之类(之后再补一个例子,让我想想...)
我一直很疑惑的类,今天终于弄懂一丢丢了
1.为什么类(class)每个方法里都有一个self?
- 任何实例数据都应该在前面加上
self
,例如,在earn
方法中使用的是self.wealth
而不是wealth
。- 在类中定义的方法应该以
self
作为第一个参数,例如,在代码中使用的是def earn(self, y)
而不是def earn(y)
。- 在类中引用的任何方法使用
self.method_name
来调用。
class Consumer:
def __init__(self,w):
self.wealth = w
def earn(self, y):
self.wealth +=y
def spend(self, x):
new_wealth = self.wealth - x
if new_wealth < 0:
print("insufficent funds")
else:
self.wealth = new_wealth
当你通过 c1.earn(10) 调用 earn 时,解释器会将实例 c1 和参数 10 传递给 Consumer.earn。以下内容是等价的:
c1.earn(10)
Consumer.earn(c1, 10)