1

在我拥有的一些 Python 模型类中寻找对自定义模型属性列表的轻松访问。我使用 MongoEngine 作为我的 ORM,但问题是一般继承和 OOP。

具体来说,我希望能够从我将在所有模型类中继承的 Mixin 类中的方法访问自定义模型属性。

考虑以下类结构:

class ModelMixin(object):
    def get_copy(self):
        """
        I'd like this to return a model object with only the custom fields
        copied.  For the City object below, it would run code equivalent to:

          city_copy = City()
          city_copy.name = self.name
          city_copy.state = self.state
          city_copy.popluation = self.population
          return city_copy

        """


class City(BaseModel, ModelMixin):
    name = orm_library.StringField()
    state = orm_library.StringField()
    population = orm_library.IntField()

这将允许以下操作:

>>> new_york = City(name="New York", state="NY", population="13000000")
>>> new_york_copy = new_york.get_copy()

但是,它必须适用于任意模型。不知何故,它必须确定在子类中定义了哪些自定义属性,实例化该子类的实例,并仅复制那些自定义属性,而不复制父 BaseModel 类(具有大量随机里面的东西我不关心

有谁知道我怎么能做到这一点?

4

1 回答 1

1

我认为您可以使用多种工具来实现这一目标(如果我下面的代码不能完全满足您的需求,您应该能够很容易地对其进行调整)。即:


class ModelMixin(object):
    def get_copy(self):

        # Get the class for the 

        C = self.__class__

        # make a new copy

        result = C()

        # iterate over all the class attributes of C
        # that are instances of BaseField

        for attr in [k for k,v in vars(C).items() if v.__class__ == BaseField]:
            setattr(result, attr, getattr(self, attr))

        return result

测试上述内容(为 MongoEngine 模型/字段创建虚拟类)

class BaseField(object):
    pass

class BaseModel(object):
    baseField = BaseField()

class City(BaseModel, ModelMixin):
    x = BaseField()
    y = BaseField()

c = City()
c.x = 3
c.y = 4
c.baseField = 5

d = c.get_copy()
print d.x # prints '3'
print d.y # prints '4'
print d.baseField # correctly prints main.BaseField, because it's not set for d
于 2013-02-22T05:41:00.217 回答