class Account(object): __slots__ = ['name', '_balance', 'trans'] num_acs = 0 @staticmethod def get_num_acs(): return Account.num_acs def __init__(self, name): self.name = name self._balance = 0 self.trans = [] Account.num_acs += 1 def get_balance(self): return self._balance def deposit(self, amount): self.trans.append(amount) self._balance += amount def withdraw(self, amount): self.trans.append(-amount) self._balance -= amount def get_all_trans(self): return tuple(self.trans) def __getitem__(self, index): return self.trans[index] def __iadd__(self, amount): self.deposit(amount) return self @property def balance(self): return self._balance @balance.setter def balance(self, amount): print 'setter' self._balance = amount def self_test(): b1 = Account('john') assert b1 is not None assert b1.get_balance() == 0 b1.deposit(100) assert b1.get_balance() == 100 b1.withdraw(10) assert b1.get_balance() == 90 assert Account.get_num_acs() == 1 assert b1.get_all_trans() == (100, -10) assert b1.get_all_trans()[0] == 100 assert b1[0] == 100 # b1.__class__.__getitem__(b1, 0) assert b1[0:2] == [100, -10] for transaction in b1: print transaction b1 += 200 assert b1.get_balance() == 290 assert list(b1) == [100, -10, 200] print 'ALL TESTS PASSED' class PAccount(Account): def __init__(self, name, amount): Account.__init__(self, name) self.deposit(amount) def plat_test(): b2 = PAccount('dave', 100) assert b2.get_balance() == 100 b3 = Account('sue') all_acs = [b2, b3] position = 0 for ac in all_acs: if isinstance(ac, Account): position += ac.get_balance() else: raise TypeError('must be Account') print position print 'ALL PLATINUM TESTS PASSED' class MyMeta(type): def __new__(cls, name, bases, att): print cls print name print bases print att if '__init__' not in att: raise TypeError('must implement __init__') return type.__new__(cls, name, bases, att) class C(object): __metaclass__ = MyMeta def _init_(self): self.mol def meta_test(): obj = C() print obj if __name__ == '__main__': #self_test() #plat_test() meta_test()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question