【发布时间】:2015-03-27 13:17:05
【问题描述】:
我(不小心)写了以下代码:
#!/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()
输出:
Withdrawing
Withdrawing
You still have 600€ euros in your account!
You still have 1000€ euros in your account!
我的问题:
1) 为什么 balance 变量虽然被声明为类(静态)变量,但它的行为却不是类(静态)变量?
2) 即使在从方法中访问balance 变量时使用self 关键字会阻止静态行为,此时会生成类变量balance 的实例副本吗? (至少这是我的推断,每个对象都有自己的副本 - 应该是类变量 - balance)
3) 通过反复试验,我发现获得(预期?)行为的一种方法是使用 @classmethod 注释方法。这是否像 Java 中那样阻止从非静态方法访问静态变量?
【问题讨论】:
标签: python class variables static