Home > database >  Difference between inheriting from object and object.__class__ for python?
Difference between inheriting from object and object.__class__ for python?

Time:08-01

I can see code below

class MetaStrategy(StrategyBase.__class__): pass

I am not sure why not just write code like below

class MetaStrategy(StrategyBase): pass

Definition schematic

class StrategyBase(DataAccessor):
    pass

class DataAccessor(LineIterator):
    pass

class LineIterator(with_metaclass(MetaLineIterator, LineSeries)):
    pass

def with_metaclass(meta, *bases):
    class metaclass(meta):
        def __new__(cls, name, this_bases, d):
            return meta(name, bases, d)
    return type.__new__(metaclass, str('temporary_class'), (), {})

CodePudding user response:

If you call self.__class__ from a subclass instance, self.__class__ will use that type of the subclass.

Any class that is expressly specified while using the class will be used naturally.

Take the example below:

class Foo(object):
    def create_new(self):
        return self.__class__()

    def create_new2(self):
        return Foo()

class Bar(Foo):
    pass

b = Bar()
c = b.create_new()
print type(c)  # We got an instance of Bar
d = b.create_new2()
print type(d)  # we got an instance of Foo

CodePudding user response:

>>> class T(type):pass
>>> class T1(T):pass
>>> class T2(metaclass=T):pass
>>> class T3(T1.__class__): pass
>>> T1
<class '__main__.T1'>
>>> T1.__bases__
(<class '__main__.T'>,)
>>> T2
<class '__main__.T2'>
>>> T2.__bases__
(<class 'object'>,)
>>> T3
<class '__main__.T3'>
>>> T3.__bases__
(<class 'type'>,)

I tested on a console, then been able to know inherit from object.class means inherit from a metaclass.

  • Related