Last active
July 19, 2016 19:44
-
-
Save kpsychas/22bb80dd3ca3e8246670 to your computer and use it in GitHub Desktop.
Recipe that uses abstract properties and abstract initialization in Python 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from abc import ABCMeta, abstractmethod, abstractproperty | |
def get_fromcls(cls, num): | |
return cls.myinit(num) | |
class Abs(object): | |
__metaclass__ = ABCMeta | |
def __init__(self, num): | |
self._num = num | |
@abstractproperty | |
def num(self): | |
pass | |
@abstractmethod | |
def myinit(cls, num): | |
pass | |
class Concr1(Abs): | |
# __init__ method has no argument | |
# but myinit must be consistent with the interface | |
def __init__(self): | |
self._num = 42 | |
@property | |
def num(self): | |
return self._num | |
@classmethod | |
def myinit(cls, num): | |
return cls() | |
class Concr2(Abs): | |
def __init__(self, num): | |
self._num = 3*num | |
@property | |
def num(self): | |
return 7*self._num | |
@classmethod | |
def myinit(cls, num): | |
return cls(2*num) | |
def main(): | |
# outputs | |
# 42 | |
# 42 | |
for cls in [Concr1, Concr2]: | |
obj = get_fromcls(cls, 1) | |
print('{}'.format(obj.num)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment