理解Python中的元类和继承

Nik*_*war 58 python inheritance metaclass

关于元类,我有些困惑.

继承

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
Run Code Online (Sandbox Code Playgroud)

与元类

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
Run Code Online (Sandbox Code Playgroud)

如上所示,实际上并没有用,只是为了理解,

我有一些问题,比如,

  1. 什么是元类的使用,我什么时候使用它?

  2. 元类和继承之间有什么区别/相似之处?

  3. 应该在哪里使用元类或继承?

dil*_*ert 40

1)什么是元类的使用以及何时使用它?

元类属于类,类属于对象.它们是类的类(因此表达式为"meta").

当您希望在OOP的正常约束之外工作时,元数据通常适用.

2)元类和继承之间有什么区别/相似之处?

元类不是对象的类层次结构的一部分,而基类是.因此,当一个对象执行时,obj.some_method()它不会搜索此方法的元类,但是元类可能在类或对象的创建过程中创建了它.

在下面的示例中,元类MetaCar为对象提供defect基于随机数的属性.该defect属性未在任何对象的基类或类本身中定义.然而,这可以仅使用类来实现.

但是(与类不同),此元类还重新创建对象; 在some_cars列表中,所有丰田都是使用Car该类创建的.元类检测到Car.__init__包含make与该名称匹配的预先存在的类的参数,因此返回该类的对象.

此外,您还会注意到在some_cars列表Car.__init__中调用make="GM".一GM类并没有在程序的评估这一点上被定义.元类在make参数中检测到该名称不存在该类,因此它创建一个并更新全局名称空间(因此它不需要使用返回机制).然后,它使用新定义的类创建对象并返回它.

import random

class CarBase(object):
    pass

class MetaCar(type):
    car_brands = {}
    def __init__(cls, cls_name, cls_bases, cls_dict):
        super(MetaCar, cls).__init__(cls_name, cls_bases, cls_dict)
        if(not CarBase in cls_bases):
            MetaCar.car_brands[cls_name] = cls

    def __call__(self, *args, **kwargs):
        make = kwargs.get("make", "")
        if(MetaCar.car_brands.has_key(make) and not (self is MetaCar.car_brands[make])):
            obj = MetaCar.car_brands[make].__call__(*args, **kwargs)
            if(make == "Toyota"):
                if(random.randint(0, 100) < 2):
                    obj.defect = "sticky accelerator pedal"
            elif(make == "GM"):
                if(random.randint(0, 100) < 20):
                    obj.defect = "shithouse"
            elif(make == "Great Wall"):
                if(random.randint(0, 100) < 101):
                    obj.defect = "cancer"
        else:
            obj = None
            if(not MetaCar.car_brands.has_key(self.__name__)):
                new_class = MetaCar(make, (GenericCar,), {})
                globals()[make] = new_class
                obj = new_class(*args, **kwargs)
            else:
                obj = super(MetaCar, self).__call__(*args, **kwargs)
        return obj

class Car(CarBase):
    __metaclass__ = MetaCar

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

    def __repr__(self):
        return "<%s>" % self.description

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

class GenericCar(Car):
    def __init__(self, **kwargs):
        kwargs["make"] = self.__class__.__name__
        super(GenericCar, self).__init__(**kwargs)

class Toyota(GenericCar):
    pass

colours = \
[
    "blue",
    "green",
    "red",
    "yellow",
    "orange",
    "purple",
    "silver",
    "black",
    "white"
]

def rand_colour():
    return colours[random.randint(0, len(colours) - 1)]

some_cars = \
[
    Car(make="Toyota", model="Prius", year=2005, color=rand_colour()),
    Car(make="Toyota", model="Camry", year=2007, color=rand_colour()),
    Car(make="Toyota", model="Camry Hybrid", year=2013, color=rand_colour()),
    Car(make="Toyota", model="Land Cruiser", year=2009, color=rand_colour()),
    Car(make="Toyota", model="FJ Cruiser", year=2012, color=rand_colour()),
    Car(make="Toyota", model="Corolla", year=2010, color=rand_colour()),
    Car(make="Toyota", model="Hiace", year=2006, color=rand_colour()),
    Car(make="Toyota", model="Townace", year=2003, color=rand_colour()),
    Car(make="Toyota", model="Aurion", year=2008, color=rand_colour()),
    Car(make="Toyota", model="Supra", year=2004, color=rand_colour()),
    Car(make="Toyota", model="86", year=2013, color=rand_colour()),
    Car(make="GM", model="Camaro", year=2008, color=rand_colour())
]

dodgy_vehicles = filter(lambda x: hasattr(x, "defect"), some_cars)
print dodgy_vehicles
Run Code Online (Sandbox Code Playgroud)

3)应该在哪里使用元类或继承?

正如本答案和评论中所提到的,在进行OOP时几乎总是使用继承.元类用于超出这些约束(参见示例),并且几乎总是不必要,但是可以使用它们实现一些非常先进且极其动态的程序流程.这既是他们的力量,也是他们的危险.

  • 这不用担心.我不知道为什么这被标记为重复; 另一个线程并没有真正说明为什么,也没有对普通的OOP实践进行比较/对比. (6认同)