Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
访问父类的最佳实践&x27;方法,但使用子类属性(Python)_Python_Oop - Fatal编程技术网

访问父类的最佳实践&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
方法
没有改变,但我正在选择在每种情况下传递给它的参数

如果有什么不清楚的,请告诉我