# newstyle.py # extend builtin type # from Guido's descrintro.html class defaultdict(dict): def __init__(self, default=None): dict.__init__(self) self.default = default def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return self.default d = defaultdict('Oops!') d[1] = 'abc' print d[1] print d[2] print # properties class BankAccount(object): def __init__(self, initial_deposit=0.0): self.balance = initial_deposit def getbalance(self): print "Calling getbalance()" return self.__balance def setbalance(self, value): print "Calling setbalance() with", value if value < 0: raise ValueError, "Can't have negative balance" else: self.__balance = float(value) balance = property(getbalance, setbalance) my_account = BankAccount(10000) try: my_account.balance = -1 except ValueError, error: print error print my_account.balance print # __slots__ class C(object): __slots__ = ['a', 'b'] x = C() x.a = 1 print "x.a:", x.a try: x.c = 2 except AttributeError: print "Can't set attributes not in __slots__"