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

前端 未结 3 1661
傲寒
傲寒 2020-12-03 00:56

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

class A(object):

          


        
3条回答
  •  猫巷女王i
    2020-12-03 01:25

    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
    

提交回复
热议问题