2015-10-07 93 views
0

先謝謝了!
我使用自定義的類時,遇到了一個問題,這裏是代碼:
類定義:如何將模型實例分配給django中的類屬性

class BaseCompetition: 
    def __init__(self, company): 
     self.company = company 
class SingleLeagueCompetition(Competition): 
    def __init__(self, company): 
    BaseCompetition.__init__(self,company) 

使用它時,就像這樣:

test_company = Company.objects.get(id=1) 
sample_single = SingleLeagueCompetition(test_company) 

'公司' 是一個模型。再次
我只是不知道什麼是錯的......

Traceback (most recent call last): 
File "/Users/littlep/myWorks/python-works/sports_with_zeal/swz/dao.py", line 32, in __init__ 
self.company = company 
File "/Users/littlep/.pythonbrew/pythons/Python-3.4.3/lib/python3.4/site-packages/django/db/models/fields/related.py", line 639, in __set__ 
if instance._state.db is None: 
AttributeError: 'SingleLeagueCompetition' object has no attribute '_state' 

感謝:
但在執行時的代碼,這樣我得到了一個錯誤!通過使用父類

class BaseCompetition: 
    def __init__(self, company): 
     self.company = company 
class SingleLeagueCompetition(BaseCompetition): 
    def __init__(self, company): 
     super().__init__(company) 

也代替調用構造函數的BaseCompetition._init_你可以用super將它綁定在孩子:

回答

1

SingleLeagueCompetition類應該從BaseCompetition繼承,像這樣。

更多參考諮詢:https://docs.python.org/3.4/library/functions.html#super

+1

這是唯一正確的答案一半,另一問題是,用戶應當聯繫'超().__的init __(公司)'代替'BaseCompetition .__的init __(個體經營,公司)' –

+0

是的,你是對的 –

+0

請添加一個關於'super()'更改的註釋,因爲它可能並不清楚爲什麼它被更改了。 (你可以鏈接到[documentation](https://docs.python.org/3.4/library/functions.html#super)作爲參考)。 –

相關問題