19. 다중상속
기반클래스검사순서를명확하게 하기 힘든경우에는클래스생성불가
>>> class X(object):
... pass
...
>>> class Y(X):
... pass
...
>>> class Z(X, Y):
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Cannot create a consistent method resolution
order (MRO) for bases X, Y
19
33. 프로퍼티
프로퍼티를설정하거나삭제하는메서드
>>> class Foo(object):
... def __init__(self, name):
... self.__name = name
... @property
... def name(self):
... return self.__name
... @name.setter
... def name(self, value):
... if not isinstance(value, str):
... raise TypeError("Must be a string")
... self.__name = value
... @name.deleter
... def name(self):
... raise TypeError("Can't delete name")
...
33
34. 프로퍼티
>>> f = Foo("John")
>>> f.name = "Jane"
>>> f.name = 42
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 10, in name
TypeError: Must be a string
>>> del f.name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 14, in name
TypeError: Can't delete name
속성name은@property 장식자를이용해읽기 전용프로퍼티로정의
@name.setter 는설정을위한추가 메서드연결
@name.deleter 는삭제를위한추가 메서드연결
추가 메서드는원본프로퍼티이름과 동일
34
65. 메타클래스
메타클래스는객체를정의하는방식에제약을가하고자할때주로사용
모든메서드에문서화문자열이존재해야하는것을강제하는메타클래스예
class DocMeta(type):
def __init__(self, name, bases, attrs):
for key, value in attrs.items():
# 특수 메서드와 private 메서드는 넘어감
if key.startswith("__"):
continue
# 호출 가능하지 않은 것은 넘어감
if not hasattr(value, "__call__"):
continue
# 문서화 문자열을 가지고 있는지 검사
if not getattr(value, "__doc__"):
raise TypeError(
"%s must have a docstring" % key)
type.__init__(self, name, bases, attrs)
65
67. 메타클래스
문서화가 필요한클래스기반클래스로Documented지정
>>> class Foo(Documented):
... def spam(self, a, b):
... print("spam")
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in __init__
TypeError: spam must have a docstring
67