Last active
March 2, 2018 09:48
-
-
Save domodomodomo/d6e0144bfa789db2b6522aaa0cd765dd to your computer and use it in GitHub Desktop.
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
from abc import ABCMeta, abstractmethod | |
class Len(metaclass=ABCMeta): | |
@abstractmethod | |
def len(self): | |
"""Return length of object.""" | |
raise NotImplementedError() | |
def checktype(method): | |
def decorated_method(*args, **kwargs): | |
val = method(*args, **kwargs) | |
if type(val) is not int: | |
raise TypeError('len method should return int') | |
else: | |
return val | |
return decorated_method | |
class Person(Len): | |
@Len.checktype | |
def len(self): | |
return 1 | |
try: | |
person = Person() | |
print(person.len()) | |
except Exception as err: | |
print(err) | |
class Dog(Len): | |
@Len.checktype | |
def len(self): | |
return 'Bow, bow!' | |
try: | |
dog = Dog() | |
print(dog.len()) # TypeError | |
except TypeError as err: | |
print(TypeError, err) | |
class Cat(Len): | |
pass | |
try: | |
cat = Cat() # NotImplementedError | |
print(cat.len()) | |
except TypeError as err: | |
print(TypeError, err) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://nihaoshijie.hatenadiary.jp/entry/2018/02/24/122308