Python 错误“<method> 缺少 1 个必需的位置参数:'self'”
Python Error " <method> missing 1 required positional argument: 'self' "
Python 的新手。尝试创建一个简单的示例来演示 2 个级别的抽象。
收到错误 TypeError: 'HPNotebook' object is not callable "
我查看了大量示例,但仍然感到困惑。
为了理解,我在代码中展示了 3 个级别。
你能指点我帮助解释这个问题以及如何消除它的地方吗?
提供有关如何纠正此问题的建议。
谢谢
from abc import abstractmethod,ABC #this is to allow abstraction. the ABC forces inherited classes to implement the abstracted methods.
class TouchScreenLaptop(ABC):
def __init__(self):
pass
@abstractmethod #indicates the following method is an abstract method.
def scroll(self): # a function within the parent
pass #specifically indicates this is not being defined
@abstractmethod #indicates the following method is an abstract method.
def click(self):
pass #specifically indicates this is not being defined
class HP(TouchScreenLaptop):
def __init__(self):
pass
@abstractmethod #indicates the following method is an abstract method.
def click(self):
pass
def scroll(self):
print("HP Scroll")
class HPNotebook(HP):
def __init__(self):
self()
def click(self):
print("HP Click")
def scroll(self):
HP.scroll()
hp1=HPNotebook()
hp1.click() #the 2 level deep inherited function called by this instance
hp1.scroll() #the 1 level deep inherited function called by this instance
只需将 HPNotebook.__init__
上的 self()
替换为 super()
,将 HPNotebook.scroll
上的 HP.scroll()
替换为 super().scroll()
。
class HPNotebook(HP):
def __init__(self):
super()
def click(self):
print("HP Click")
def scroll(self):
super().scroll()
此外,检查 this link 以更好地理解 python 继承。
Python 的新手。尝试创建一个简单的示例来演示 2 个级别的抽象。 收到错误 TypeError: 'HPNotebook' object is not callable "
我查看了大量示例,但仍然感到困惑。
为了理解,我在代码中展示了 3 个级别。
你能指点我帮助解释这个问题以及如何消除它的地方吗?
提供有关如何纠正此问题的建议。
谢谢
from abc import abstractmethod,ABC #this is to allow abstraction. the ABC forces inherited classes to implement the abstracted methods.
class TouchScreenLaptop(ABC):
def __init__(self):
pass
@abstractmethod #indicates the following method is an abstract method.
def scroll(self): # a function within the parent
pass #specifically indicates this is not being defined
@abstractmethod #indicates the following method is an abstract method.
def click(self):
pass #specifically indicates this is not being defined
class HP(TouchScreenLaptop):
def __init__(self):
pass
@abstractmethod #indicates the following method is an abstract method.
def click(self):
pass
def scroll(self):
print("HP Scroll")
class HPNotebook(HP):
def __init__(self):
self()
def click(self):
print("HP Click")
def scroll(self):
HP.scroll()
hp1=HPNotebook()
hp1.click() #the 2 level deep inherited function called by this instance
hp1.scroll() #the 1 level deep inherited function called by this instance
只需将 HPNotebook.__init__
上的 self()
替换为 super()
,将 HPNotebook.scroll
上的 HP.scroll()
替换为 super().scroll()
。
class HPNotebook(HP):
def __init__(self):
super()
def click(self):
print("HP Click")
def scroll(self):
super().scroll()
此外,检查 this link 以更好地理解 python 继承。