[英]How to execute part of “__init__” after __init__ of subclass in python?
I have a problem in Python, which I feel should theoretically be possible to solve, but perhaps not in practice. 我在Python中遇到问题,从理论上讲,我认为应该可以解决这个问题,但实际上可能无法解决。 I have a class which has a lot of different subclasses.
我有一个包含许多不同子类的类。 Each object of the objects of the subclasses get a name based on some properties that are unique to the subclass.
子类的对象的每个对象都会基于子类唯一的某些属性获得名称。 After that name is defined, I want for each of them to execute the same method, but based on that name.
定义该名称后,我希望它们每个都执行相同的方法,但要基于该名称。 So I'd like to put that in the
__init__
of the parent class, but that bit should be executed AFTER execution of the subclass' __init__
. 因此,我想将其放在父类的
__init__
中,但应在子类的__init__
执行之后执行该位。 I suppose I could call some method from the parent class in each of the subclasses' __init__
at the end, but then I would be copying code and that doesn't feel right to me. 我想我可以在每个子类的
__init__
最后从父类中调用某个方法,但是那样我将复制代码,这对我来说感觉不对。 So I was wondering if there's a more elegant solution. 所以我想知道是否有更优雅的解决方案。
class Cell(object):
def __init__(self, some_essential_property=1):
self.some_essential_property = some_essential_property
# New execute subclass __init__, so that it can make the name
# Then:
self.name = self.make_name()
print(self.name)
def make_name(self):
return 'no_special_name'
class Muscle_cell(Cell):
def __init__(self, strength='huge'):
super().__init__()
self.strength = 'huge'
def make_name(self):
return 'muscle_with_' + self.strength + '_strength_and_' + str(self.some_essential_property)
M1 = Muscle_cell()
This will raise an error because strength isn't known as an attribute yet. 这将引发错误,因为强度尚未被称为属性。 That's why I'd like to execute certain lines immediately after the subclass
__init__
. 这就是为什么我想在子类
__init__
之后立即执行某些行。
A superclass should not depend on a subclass, there are other (more OOP ways) to do what you want in Python. 超类不应该依赖于子类,还有其他(更多的OOP方法)可以在Python中完成您想要的事情。
import abc
class Cell(object):
def __init__(self, some_essential_property=1):
self.some_essential_property = some_essential_property
@property
def name(self):
return self.make_name()
@abc.abstractmethod
def make_name(self):
pass
class Muscle_cell(Cell):
def __init__(self, strength='huge'):
super().__init__()
self.strength = 'huge'
def make_name(self):
return 'muscle_with_' + self.strength + '_strength_and_' + str(self.some_essential_property)
M1 = Muscle_cell()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.