先谢谢!
我在使用自定义类时遇到了问题,这里是代码:
类定义:
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'
再次感谢!
答案 0 :(得分:1)
您的SingleLeagueCompetition
课程应该继承BaseCompetition
,如下所示:
class BaseCompetition:
def __init__(self, company):
self.company = company
class SingleLeagueCompetition(BaseCompetition):
def __init__(self, company):
super().__init__(company)
也可以通过使用父类BaseCompetition._init_
来代替调用构造函数,您可以使用super
将其绑定到子级中。
更多参考咨询:https://docs.python.org/3.4/library/functions.html#super