访问父类的最佳实践&x27;方法,但使用子类属性(Python)
我有很多类,我希望它们都能从一个单亲类继承一个方法。但是,对于每个子级,此方法的输入将不同-来自子级的类属性访问父类的最佳实践&x27;方法,但使用子类属性(Python),python,oop,Python,Oop,我有很多类,我希望它们都能从一个单亲类继承一个方法。但是,对于每个子级,此方法的输入将不同-来自子级的类属性 class Parent: def __init__(self): def method(self, a, b): return F(a, b) class ChildA(Parent): x = Foo y = Bar def __init__(self, thing): self.attribute = thing class ChildB(Par
class Parent:
def __init__(self):
def method(self, a, b):
return F(a, b)
class ChildA(Parent):
x = Foo
y = Bar
def __init__(self, thing):
self.attribute = thing
class ChildB(Parent)
x = Bar
y = Foo
def __init__(self, thing):
self.attribute = thing
从这里我希望能够调用,例如:ChildAInstance.method(x,y)
或ChildBInstance.method(x,y)
我是从正确的角度来处理这个问题的吗?理想情况下,我需要将其作为一个方法而不是一个独立的函数,因为该方法需要修改子类实例中的self.attributes 如果我很了解您的问题,OOP中的继承将为您解决这个问题 子类继承
方法
,因为它在父类
中定义。当您在其中一个子类上调用它时,由您来传递要使其工作的参数
看看这个例子:
类父级:
定义初始化(自):
通过
def方法(自身、x、y):
打印(“你好,我是x:%s”%x)
打印(“我是y:%s”%y)
儿童A类(家长):
x='foo'
y=‘巴’
B类儿童(家长):
x=‘巴’
y='foo'
如果您运行:
如果名称=“\uuuuu main\uuuuuuuu”:
childA=childA()
childB=childB()
childA.method(childA.x,childA.y)
childB.method(childB.x,childB.y)
你应该得到:
Hello I'm x: foo
And I'm y: bar
Hello I'm x: bar
And I'm y: foo
方法
没有改变,但我正在选择在每种情况下传递给它的参数
如果有什么不清楚的,请告诉我