Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.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
Python 如何重写父类?_Python_Python 3.x_Class_Oop - Fatal编程技术网

Python 如何重写父类?

Python 如何重写父类?,python,python-3.x,class,oop,Python,Python 3.x,Class,Oop,我有两门课: class Parent(object): def __init__(self): self.a = 0 self.b = self.a + 1 class Child(Parent): def __init__(self): super().__init__() self.a = 1 print(Child().b) 输出是1(0+1),但我希望有2(1+1)。如何获得这样的结果?在父级之外分配

我有两门课:

class Parent(object):
    def __init__(self):
        self.a = 0
        self.b = self.a + 1

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.a = 1

print(Child().b)

输出是
1
0+1
),但我希望有
2
1+1
)。如何获得这样的结果?

父级之外分配
属性。
初始属性:

class Parent(object):
    a = 0
    def __init__(self):
        self.b = self.a + 1

class Child(Parent):
    def __init__(self):
        self.a = 1
        super().__init__()

print(Child().b)

如果未提供参数,则可以使用
关键字参数来设置父类中
a
的值:

class Parent(object):
    def __init__(self, a=None):
        if a is None:
            self.a = 0
        self.b = self.a + 1

class Child(Parent):
    def __init__(self):
        self.a = 1
        super().__init__(self.a)

parent = Parent()
child = Child()
print(parent.a, parent.b) 
print(child.a, child.b)
输出: 另一种方法可以使用类变量:

class Parent(object):
    a = 0
    def __init__(self):
        self.a = self.__class__.a
        self.b = self.a + 1

class Child(Parent):
    a = 1
    def __init__(self):
        super().__init__()

parent = Parent()
child = Child()
print(parent.a, parent.b) 
print(child.a, child.b)
输出: 在上面的例子中,使用类变量,您完全可以在子类中不使用
\uuuuu init\uuuu
方法:(这可能适用于,也可能不适用于您的实际用例)


如果你能解释一下为什么这样做,以及为什么最初的方法失败了,这将是很有帮助的。你的代码是错误的,因为每次父级
\uuuu init\uuuu
运行
a
属性时,都会得到0值,这就是为什么你通过调用
super()得到1而不是2的原因
你调用父方法
\uuuuu init\uuuu
我在你的回答中是指,而不是在评论中。谢谢。对于您正在使用的代码,1是
b
的预期值,因为
子对象。
首先调用
父对象。
然后设置
self.a
,这太晚了。
class Parent(object):
    a = 0
    def __init__(self):
        self.a = self.__class__.a
        self.b = self.a + 1

class Child(Parent):
    a = 1
    def __init__(self):
        super().__init__()

parent = Parent()
child = Child()
print(parent.a, parent.b) 
print(child.a, child.b)
0 1
1 2
class Parent(object):
    a = 0
    def __init__(self):
        self.a = self.__class__.a
        self.b = self.a + 1

class Child(Parent):
    a = 1