# Defining a Base class to be shared among many other classes later:
class Base(dict):
"""Base is the base class from which all the class will derrive.
"""
name = 'name'
def __init__(self):
"""Initialise Base Class
"""
dict.__init__(self)
self[Base.name] = ""
# I create an instance of the Base class:
my_base_instance = Base()
# Since a Base class inherited from a build in 'dict' the instance of the class is a dictionary. I can print it out with:
print my_base_instance Results to: {'name': ''}
# Now I am defining a Project class which should inherit from an instance of Base class:
class Project(object):
def __init__(self):
print "OK"
self['id'] = ''
# Trying to create an instance of Project class and getting the error:
project_class = Project(base_class)
TypeError: __init__() takes exactly 1 argument (2 given)
0
A
回答
1
有兩個錯誤在你的代碼:
1)類繼承
class Project(Base): # you should inherit from Base here...
def __init__(self):
print "OK"
self['id'] = ''
2)實例的定義(您__init__
並不需要任何明確的參數,而且可以肯定不是祖先類)
project_class = Project() # ...and not here since this is an instance, not a Class
1
當你正在實例化一個類時,你不需要傳入base_class
。這是定義完成的。 __init__
只需要1個參數,即self
,並且是自動的。你只需要調用
project_class = Project()
1
對於項目從基本繼承,你不應該從對象繼承它,但來自基地即class Project(Base)
。當您實例化Project類時,您會收到TypeError: init() takes exactly 1 argument (2 given)
錯誤,因爲構造函數只帶1個參數(self
),並且您也通過base_class
。由python隱式傳遞'self'
。
相關問題
- 1. 繼承Python類繼承docstrings
- 2. Python類繼承
- 3. Python:類繼承
- 4. Python類繼承__init__
- 5. Python子類繼承
- 6. Python類繼承,attributeError
- 7. python __str__繼承類
- 8. Python類繼承MonkeyDevice
- 9. 子類Python類繼承
- 10. Python中的類繼承
- 11. 的Python:嵌套類繼承
- 12. Python 2類的繼承
- 13. python中的類和繼承
- 14. Python類繼承初始化
- 15. python類繼承瞭解
- 16. 在Python中繼承類?
- 17. Python Tkinter類繼承問題
- 18. Python參數類繼承
- 19. Python繼承:返回子類
- 20. python類繼承def __init位?
- 21. Python,類和繼承測試
- 22. Python類 - 屬性繼承
- 23. Python繼承基類變量
- 24. Python類繼承,__init__和cls
- 25. 繼承類屬性(python)
- 26. python類互相繼承
- 27. Python類屬性繼承
- 28. Python的繼承
- 29. 其他繼承類中的繼承類
- 30. 具有類繼承性的Python元類
您必須在定義類('class Project(Base)')時聲明繼承,而不是在實例化時聲明繼承。 – Hyperboreus