如何为抽象基 class 实现构造函数?
How to implement a constructor for an abstract base class?
我正在尝试编写一个基础抽象 class,它具有一些将使用构造函数初始化的属性。到目前为止我有这个:
from abc import ABC, abstractmethod
class A(ABC):
def __init__(self, n, *params):
self.n = n
self.initialize_params(*params) #I want to do this in all subsclasses of A
def initialize_params(self, *params)
pass
@abstractmethod
def do(self):
pass
class B(A):
def __init__(self, m, n, *super_params):
self.m = m
super(A, self).__init__(n, *super_params)
def do(self):
print("this is B")
但这会抛出 TypeError
,因为在 B 的 __init__
中实例化了 A。正确的做法是什么?
你似乎有几个错误:
from abc import ABC, abstractmethod
class A(ABC):
def __init__(self, n, *params):
self.n = n
self.initialize_params(*params) #I want to do this in all subsclasses of A
def initialize_params(self, *params):
pass
@abstractmethod
def do(self):
pass
class B(A):
def __init__(self, m, n, *super_params):
self.m = m
super().__init__(n, *super_params) # correct way to use super() to call init
def do(self):
print("this is B")
b = B(1,2)
b.do()
请注意,您错过了 initialize_params()
前面的 self.
,而且您似乎没有正确使用 super()
。
我正在尝试编写一个基础抽象 class,它具有一些将使用构造函数初始化的属性。到目前为止我有这个:
from abc import ABC, abstractmethod
class A(ABC):
def __init__(self, n, *params):
self.n = n
self.initialize_params(*params) #I want to do this in all subsclasses of A
def initialize_params(self, *params)
pass
@abstractmethod
def do(self):
pass
class B(A):
def __init__(self, m, n, *super_params):
self.m = m
super(A, self).__init__(n, *super_params)
def do(self):
print("this is B")
但这会抛出 TypeError
,因为在 B 的 __init__
中实例化了 A。正确的做法是什么?
你似乎有几个错误:
from abc import ABC, abstractmethod
class A(ABC):
def __init__(self, n, *params):
self.n = n
self.initialize_params(*params) #I want to do this in all subsclasses of A
def initialize_params(self, *params):
pass
@abstractmethod
def do(self):
pass
class B(A):
def __init__(self, m, n, *super_params):
self.m = m
super().__init__(n, *super_params) # correct way to use super() to call init
def do(self):
print("this is B")
b = B(1,2)
b.do()
请注意,您错过了 initialize_params()
前面的 self.
,而且您似乎没有正确使用 super()
。