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

Question:

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
Asked By: ikostia

||

Answers:

Since a class is an instance of a metaclass, one way is to use a custom metaclass:

>>> Meta = type('Meta', (type,), {'__repr__': lambda cls: 'class A'})
>>> A = Meta('A', (object,), {'__repr__': lambda self: 'instance of class A'})
>>> A
class A
>>> A()
instance of class A
Answered By: Eryk Sun

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):n __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].

Answered By: Eli Collins

try this:

class Lengthy:
    x = 5
    @classmethod
    def __len__(cls):
        return cls.x

The @classmethod allows you to call it directly on the class, but your len implementation won’t be able to depend on any instance variables:

a = Lengthy()
len(a)
Answered By: Ankhara33

I fail to see how the Syntax specifically is important, but if you really want a simple way to implement it, just is the normal len(self) that returns len(inst) but in your implementation make it return a class variable that all instances share:

class A:
    my_length = 5
    def __len__(self):
        return self.my_length

and you can later call it like that:

len(A()) #returns 5

obviously this creates a temporary instance of your class, but length only makes sense for an instance of a class and not really for the concept of a class (a Type object).

Editing the metaclass sounds like a very bad idea and unless you are doing something for school or to just mess around I really suggest you rethink this idea..

Answered By: Nadav Porat
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.