博文

目前显示的是 十一月, 2017的博文

ch39元类(python)

class Extras:     def extra(self, args):              # Normal inheritance: too static         ... class Client1(Extras): ...              # Clients inherit extra methods class Client2(Extras): ... class Client3(Extras): ... X = Client1()                           # Make an instance X.extra()                               # Run the extra methods def extra(self, arg): ... class Client1: ...                      # Client augments: too distributed if required():     Client1.extra = extra class Client2: ... if required():     Client2.extra = extra class Client3: ... if required():     Client3.extra = extra X = Client1() X.extra() ...

ch38装饰器(python)

# NOTE: for the last 2 chapters, I am mostly including working # code examples here; to expand pseudocode listings early in # the chapters, type their code parts in your editor. def decorator(cls):                             # On @ decoration     class Wrapper:         def __init__(self, *args):              # On instance creation             self.wrapped = cls(*args)         def __getattr__(self, name):            # On attribute fetch             return getattr(self.wrapped, name)     return Wrapper @decorator class C:                             # C = decorator(C)     def __init__(self, x, y):        # Run by ...