标签云

微信群

扫码加入我们

WeChat QR Code

了解Python [复制]元类和继承

This question already has an answer here:

I have some confusion regarding meta-classes.

With inheritance

class AttributeInitType(object):

   def __init__(self,**kwargs):
       for name, value in kwargs.items():
          setattr(self, name, value)

class Car(AttributeInitType):

    def __init__(self,**kwargs):
        super(Car, self).__init__(**kwargs)
    @property
    def description(self):
       return "%s %s %s %s" % (self.color, self.year, self.make, self.model)

c = Car(make='Toyota', model='Prius', year=2005, color='green')
print c.description

With meta class

class AttributeInitType(type):
   def __call__(self, *args, **kwargs):
       obj = type.__call__(self, *args)
       for name, value in kwargs.items():
           setattr(obj, name, value)
       return obj

class Car(object):
   __metaclass__ = AttributeInitType

   @property
   def description(self):
       return "%s %s %s %s" % (self.color, self.year, self.make, self.model)


c = Car(make='Toyota', model='Prius', year=2005,color='blue')
print c.description

As above example is not useful as practically but just for understanding,

I have some questions Like,

  1. What is use of metaclass and when do I use it?

  2. What is the difference/similarity between a meta class and inheritance?

  3. Where should one use a meta class or inheritance?


Rule of thumb: If you can do it without metaclasses, don't use metaclasses.

2018年06月19日07分01秒

If you have to ask whether or not you need a metaclass, you don't need a metaclass.

2018年06月20日07分01秒

Thanks dilbert .. gr8 explanation This difference can be noted from : with metaclass, issubclass(Car,AttributeInitType) returns -> False

2018年06月20日07分01秒

That's no worries. I don't know why this was marked as duplicate; the other thread didn't really say WHY nor give a compare/contrast to ordinary OOP practices.

2018年06月20日07分01秒