簡體   English   中英

sqlalchemy基類引發“在舊樣式類上使用屬性”錯誤

[英]sqlalchemy Base Class raises “use of property on an old style class” error

想知道sqlalchemy中的Base是否繼承自Object 請參閱下面的詳細信息。

當前使用Python3和SQLAlchemy 0.8

在我的項目中,我用(對象)聲明了一個新樣式類,然后繼續使用“屬性”在類中定義屬性。 該類工作正常,“下面的示例代碼”

class LoadFile(object):

    def _set_year(self, value): 
        '''set the year'''    
        value = value[6:10]
        if valid_integer(value) != True:
            raise Exception ("File Name Error: The year value should be a numeral")
        self._year = value
    def _get_year(self):
        '''get the year'''
        return self._year

    year = property(_get_year, _set_year)

隨着項目的發展,我已經開始使用SQLAlchemy並運行該類,它引發了錯誤

class LoadFile(object):
    __tablename__ = "load_file"
    id = Column(Integer(10), primary_key = True)
    file_name = Column(String(250), nullable = False, unique = True)
    file_path = Column(String(500), nullable = False)
    date_submitted = Column(DateTime, nullable = False)
    submitted_by = Column(String, nullable = False)

    def _set_year(self, value): 
        '''set the year'''    
        value = value[6:10]
        if valid_integer(value) != True:
            raise Exception ("File Name Error: The year value should be a numeral")
        self._year = value
    def _get_year(self):
        '''get the year'''
        return self._year

    year = property(_get_year, _set_year)

它引發的錯誤是:

AttributeError: 'LoadFile' object has no attribute '_sa_instance_state'

File "/usr/local/lib/python3.2/dist-packages/SQLAlchemy-0.8.0b2-py3.2.egg/sqlalchemy/orm/session.py", line 1369, in add
raise exc.UnmappedInstanceError(instance)
sqlalchemy.orm.exc.UnmappedInstanceError: Class '__main__.LoadFile' is not mapped

所以我注意到我不是從“ Base ”繼承的,所以我將類更改為:

class LoadFile(Base):

這樣,sqlalchemy可以正常工作,並且表已成功創建。 但是,我現在注意到我在日食說明中收到警告

Use of "property" on an old style class"

所以我想知道, Base是否不繼承自Object? 以為我早就讀過了。 否則,為什么我現在要收到此“警告”。 我知道我可以忽略它,但是只是想找出確切原因,也許是如何糾正它。

謝謝。

更新

我繞過使用裝飾器,如下所示。 這樣,上面的“警告”消失了

@property
def year(self):
    '''get the year'''
    return self._year
@year.setter
def year(self, value): 
    '''set the year'''
    if valid_integer(value) != True:
        raise Exception ("File Name Error: The year value should be a numeral")
    self._year = value

這樣就可以解決警告了。 但是我仍然不明白為什么以前的方法會發出警告...。而且,我也不十分確定哪種方法是使用裝飾器或上一個方法的最佳方法。

Python 3中不存在舊式類,因此警告是虛假的。 在Eclipse中檢查Preferences和Project Properties,也許有對Python 2.x的引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM