나는 __prepare__
함수에 대해 가르칩니다. 그리고 PEP3115메타 클래스 및 __prepare__()
# The custom dictionary
class member_table(dict):
def __init__(self):
self.member_names = []
def __setitem__(self, key, value):
# if the key is not already defined, add to the
# list of keys.
if key not in self:
self.member_names.append(key)
# Call superclass
dict.__setitem__(self, key, value)
# The metaclass
class OrderedClass(type):
# The prepare function
@classmethod
def __prepare__(metacls, name, bases): # No keywords in this case
return member_table()
# The metaclass invocation
def __new__(cls, name, bases, classdict):
# Note that we replace the classdict with a regular
# dict before passing it to the superclass, so that we
# don't continue to record member names after the class
# has been created.
result = type.__new__(cls, name, bases, dict(classdict))
result.member_names = classdict.member_names
return result
class MyClass(metaclass=OrderedClass):
# method1 goes in array element 0
def method1(self):
pass
# method2 goes in array element 1
def method2(self):
pass
내 질문에이 조각이 줄에 있습니다 참조 : result.member_names = classdict.member_names
어떻게 변수가 member_table
클래스의 속성을 얻을 classdict
수 있을까? __prepare__
함수는 member_table의 인스턴스를 반환하지만, member_table()
과 classdict.member_names
사이의 링크는 어떻게 생성되는 걸까요?
여러분 모두에게 감사드립니다.
답변 해 주셔서 감사합니다. 하나 더 작은 질문 -'__prepare__' 함수가 항상 dict 또는 장식 된 dict 유형 (다른 유형이 아님) 인 네임 스페이스를 반환하는지 확인할 수 있습니까? – luoshao23
"확인"이란 무엇을 의미합니까? '__prepare__'를 저작하고 그것이 무엇을 반환 하는지를 알아야합니다. 완전한 매핑 객체처럼 행동 할 필요가 없다면,'__setitem__' 만 필요하고, mclass'__init__'의 코드는 어떻게 처리해야 하는지를 알고 있어야합니다. – jsbueno
(질문에 대한 답변을 얻은 경우, 대답을 수락하는 것을 잊지 마십시오) – jsbueno