2013-02-21 86 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