我(不小心)写了以下代码:#!/usr/bin/python3.4
class Account:
balance = 1000
def withdraw(self, amount):
print('Withdrawing')
if(amount > self.balance):
print("You cannot withdraw that amount!")
else:
self.balance -= amount
def checkBalance(self):
if (self.balance == 0):
print("Your account is empty.")
else:
print("You still have ", str(self.balance) + "€ euros in your account!")
def Main():
account1 = Account()
account2 = Account()
account1.withdraw(100)
account1.withdraw(300)
account1.checkBalance()
account2.checkBalance()
if __name__ == "__main__":
Main()
输出:
^{pr2}$
我的问题:
1)为什么balance变量没有作为类(静态)变量进行声明?在
2)即使在方法内访问balance变量时使用self关键字阻止了静态行为,那么此时是否生成了类变量balance的实例副本?(至少这是我推断的,每个对象都有它自己的-应该是类变量-balance)的副本)
3)通过反复试验,我发现了一种方法来获得(预期的?)行为是用@classmethod注释方法。这是不是像Java中的s.th那样阻止从非静态方法访问静态变量?在
我知道this和{a2}的帖子,但他们并不涉及上述含义。在