So lange, wie Sie in Python 3.x nur daran interessiert sind (und von den leeren Klammern in Ihrer Erklärung Klasse Ich werde Ich nehme an, Sie könnten es sein), dann gibt es tatsächlich eine einfache Möglichkeit, dies ohne Dekoratoren zu tun: Python 3 ermöglicht es Ihnen, Ihr eigenes Wörterbuch wie ein Objekt zur Verfügung zu stellen, während die Klasse definiert ist.
Der folgende Code aus PEP3115 ist bis auf den letzten paar Zeilen, die ich aus den Verfahren zu drucken, um das hinzugefügt:
# 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
x = MyClass()
print([name for name in x.member_names if hasattr(getattr(x, name), '__call__')])
Jede Art und Weise, es zu tun, wenn ich über den Auftrag nicht kümmern? – curious
Sicher, ich werde die Antwort bearbeiten. –