2013-02-21 87 views
1

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

具体而言,我希望能够从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类复制内置属性和方法(其中有大量的它随机塞入我不关心。

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

+0

它看起来像你想从对象,而不是让所有的'实例Variables'这个类的'自定义属性',这是正确的吗? – 2013-02-21 17:20:57

+0

是的,我认为是。至于措辞,这是来自python文档:“数据属性对应于Smalltalk中的”实例变量“,以及C++中的”数据成员“。所以我认为我们正在谈论同样的事情,是的。 – 2013-02-21 17:23:22

回答

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