Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

python - Is there a way to implement methods like __len__ or __eq__ as classmethods?

It is pretty easy to implement __len__(self) method in Python so that it handles len(inst) calls like this one:

class A(object):

  def __len__(self):
    return 7

a = A()
len(a) # gives us 7

And there are plenty of alike methods you can define (__eq__, __str__, __repr__ etc.). I know that Python classes are objects as well.

My question: can I somehow define, for example, __len__ so that the following works:

len(A) # makes sense and gives some predictable result
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...