2015-10-07 95 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)作为参考)。 –

相关问题