Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from abc import ABCMeta, abstractmethod
- import random
- class BaseSource:
- __metaclass__ = ABCMeta
- @abstractmethod
- def get(self):
- pass
- class ManualSrc(BaseSource):
- def get(self):
- return float(raw_input('gimme a number - '))
- class RandomSrc(BaseSource):
- def get(self):
- return random.random()
- class Source(BaseSource):
- """generic Source choice"""
- def __new__(BaseSource, choice):
- if choice == 0:
- return ManualSrc()
- elif choice == 1:
- return RandomSrc()
- else:
- raise ValueError('source choice parameter {} not valid'.format(choice))
- if __name__ == '__main__':
- for use_src in range(4):
- print 'using source choice {}'.format(use_src)
- src = Source(use_src)
- print src.get()
- ## [ . . . ]
- class RandomSrc(BaseSource):
- def get(self):
- return random.random()
- def create_source(choice):
- if choice == 0:
- return ManualSrc()
- elif choice == 1:
- return RandomSrc()
- else:
- raise ValueError('source choice parameter {} not valid'.format(choice))
- if __name__ == '__main__':
- for use_src in range(4):
- print 'using source choice {}'.format(use_src)
- src = create_source(use_src)
- print src.get()
- ## [ . . . ]
- class RandomSrc(BaseSource):
- def get(self):
- return random.random()
- class WhateverSrc(BaseSource):
- def get(self):
- return "Foo Bar??"
- def create_source(choice):
- if choice == 0:
- return ManualSrc()
- elif choice == 1:
- return RandomSrc()
- elif choice == 2:
- return WhateverSrc()
- else:
- raise ValueError('source choice parameter {} not valid'.format(choice))
- import random
- class ManualSrc(object):
- def get(self):
- return float(raw_input('gimme a number - '))
- class RandomSrc(object):
- def get(self):
- return random.random()
- class BreakingSrc(object):
- pass
- def create_source(choice):
- if choice == 0:
- return ManualSrc()
- elif choice == 1:
- return RandomSrc()
- elif choice == 2:
- return BreakingSrc()
- else:
- raise ValueError('source choice parameter {} not valid'.format(choice))
- if __name__ == '__main__':
- for use_src in range(4):
- print 'using source choice {}'.format(use_src)
- src = create_source(use_src)
- print src.get()
- using source choice 0
- gimme a number - 1
- 1.0
- using source choice 1
- 0.702223268052
- using source choice 2
- Traceback (most recent call last):
- File "./stack26.py", line 28, in <module>
- print src.get()
- AttributeError: 'BreakingSrc' object has no attribute 'get'
- from abc import ABCMeta, abstractmethod
- import random
- import inspect
- available_srcs = []
- def register(newclass):
- if inspect.isabstract(newclass):
- print ("newclass %s is abstract, and has abstract"
- " methods: %s. Refusing to register"
- % (newclass, newclass.__abstractmethods__))
- return
- if newclass not in available_srcs:
- available_srcs.append(newclass)
- print "Registered %s as available source" % newclass
- class MyMetaClass(ABCMeta):
- def __new__(cls, clsname, bases, attrs):
- newclass = super(MyMetaClass, cls).__new__(cls, clsname, bases, attrs)
- register(newclass) # here is your register function
- return newclass
- class BaseSource(object):
- __metaclass__ = MyMetaClass
- @abstractmethod
- def get(self):
- pass
- class ManualSrc(BaseSource):
- def get(self):
- return float(raw_input('gimme a number - '))
- class RandomSrc(BaseSource):
- def get(self):
- return random.random()
- if __name__ == '__main__':
- for use_src in range(4):
- print 'using source choice {}'.format(use_src)
- src = available_srcs[use_src]()
- print src.get()
- >>> import logging
- >>> log = logging.getLogger('hello')
- >>> vars(log)
- {'name': 'hello', 'parent': <logging.RootLogger object at 0x17ce850>, 'handlers': [], 'level': 0, 'disabled': 0, 'manager': <logging.Manager object at 0x17ce910>, 'propagate': 1, 'filters': []}
- >>> type(log)
- <class 'logging.Logger'>
- a = A()
- a.x = 5
- print "a.x is %s" % a.x
- class B(object):
- def __init__(self):
- self.x = 10
- @property
- def x(self):
- return "I ain't returning x but something weird, and x is %s... FYI"
- % self._x
- @x.setter
- def x(self, x):
- self._x = int(self._x if hasattr(self, '_x') else 0 + 2 * x)
- def A():
- return B()
- >>> class C(object):
- ... pass
- ...
- >>> vars(C)
- dict_proxy({'__dict__': <attribute '__dict__' of 'C' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'C' objects>, '__doc__': None})
- >>> type(C)
- <type 'type'>
- >>> def get_me_a_c_class():
- ... return C
- ...
- >>> my_class = get_me_a_c_class()
- >>> my_instance = my_class()
- >>> type(my_instance)
- <class '__main__.C'>
- >>> type(get_me_a_c_class)
- <type 'function'>
- >>> vars(get_me_a_c_class)
- {}
- >>> get_me_a_c_class.random_attribute = 5
- >>> print "Did I just put an attribute to a FUNCTION??: %s" % get_me_a_c_class.random_attribute
- Did I just put an attribute to a FUNCTION??: 5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement