What you're looking for is called a "metaclass"... just like a
is an instance of class A
, A
is an instance of class as well, referred to as a metaclass. By default, Python classes are instances of the type
class (the only exception is under Python 2, which has some legacy "old style" classes, which are those which don't inherit from object
). You can check this by doing type(A)
... it should return type
itself (yes, that object has been overloaded a little bit).
Metaclasses are powerful and brain-twisting enough to deserve more than the quick explanation I was about to write... a good starting point would be this stackoverflow question: What is a Metaclass.
For your particular question, for Python 3, the following creates a metaclass which aliases len(A)
to invoke a class method on A:
class LengthMetaclass(type):
def __len__(self):
return self.clslength()
class A(object, metaclass=LengthMetaclass):
@classmethod
def clslength(cls):
return 7
print(len(A))
(Note: Example above is for Python 3. The syntax is slightly different for Python 2: you would use class A(object):
__metaclass__=LengthMetaclass
instead of passing it as a parameter.)
The reason LengthMetaclass.__len__
doesn't affect instances of A
is that attribute resolution in Python first checks the instance dict, then walks the class hierarchy [A, object]
, but it never consults the metaclasses. Whereas accessing A.__len__
first consults the instance A
, then walks it's class hierarchy, which consists of [LengthMetaclass, type]
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…