如何在多个子对象 class 中使用父对象 class 在 python 中的子对象 class 中使用父对象中的所有设置变量

How to use parent class object in multiple child class to use all set variables in parent object in children class in python

class A():
    def __init__(self, a, b):
        self.a = a
        self.b = b

class B(A):
    def __init__(self, c):
        self.c = c

class C(A):
    def __init__(self, d):
        self.d = d


temp = A("japan", "Germany")
childtemp1 = B("California")
childtemp2 = C("Delhi")

一段时间后,我将 class B 和 C 用于两个不同的目的,但它们都有一些相同的公共变量,这些变量存在于 class A 中,并且 class A 已经实例化.

我在一些更不同的 classes 中使用这个 class B 和 C,我想在其中使用 class(A 和 B)和 class 的变量(A 和 C)。

如果您想使用 childtemp1 访问 a, b, c 您需要在创建对象时传递 a, b, c

class A():
    def __init__(self, a, b):
        self.a = a
        self.b = b

class B(A):
    def __init__(self, a, b, c):
        self.c = c
        A.__init__(self, a, b)

class C(A):
    def __init__(self, a, b, d):
        self.d = d
        A.__init__(self, a, b)

childtemp1 = B("Japan", "Germany", "California")
childtemp2 = C("Japan", "Germany", "Delhi")
print(childtemp1.a, childtemp1.b, childtemp1.c)
print(childtemp2.a, childtemp2.b, childtemp2.d)

输出:

Japan Germany California
Japan Germany Delhi

您可以使用父对象

创建子对象class
class A():
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return "a = " + str(self.a) + " b = " + str(self.b) 

class B(A):

    def __init__(self, parent, c):
        self.c = c
        A.__init__(self, parent.a, parent.b)

    def __repr__(self):
      return  super().__repr__()+ " c = " + str(self.c)

class C(A):

    def __init__(self, parent, d):
        self.d = d
        A.__init__(self, parent.a, parent.b)

    def __repr__(self):
        return  super().__repr__()+ " d = " + str(self.d)

temp = A("Japan", "Germany")
childtemp1 = B(temp, 'India')
childtemp2 = C(temp, 'USA')

print(childtemp1)
print(childtemp2)

输出:

a = Japan b = Germany c = India
a = Japan b = Germany d = USA

这个例子可能会帮助你理解

class A():
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def print_variables(self):
        print(self.a , " ", self.b, end = "  ")

class B(A):
    def __init__(self, a,b,c):
        super(B, self).__init__(a,b)
        self.c = c

    def show(self):
        super(B, self).print_variables()
        print(self.c)

childtemp1 = B("a","b","c")

childtemp1.show()

输出

a   b  c