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

标签 python class object-oriented-analysis

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")

有时我将类 B 和 C 用于两个不同的目的,但它们都有一些相同的公共(public)变量,这些变量存在于类 A 中,并且类 A 已经实例化。

我在一些更多不同的类中使用B类和C类,我想在这些类中使用类(A和B)和类(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 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

关于python - 如何在多个子类中使用父类对象以在python中的子类中使用父类对象中的所有设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61162188/

相关文章:

java - 避免处理 config.properties 的 Java 类文件中的静态方法和变量

python - TensorFlow 分布式运行时模型并行 CIFAR-10

java - 实现 java Comparable<T> 类的问题

python - 是否可以选择将哪些 kwargs 传递给 python 中的父类(super class)?

PHP::完全限定方法文字到字符串

c# - 当我只希望某些派生类可以访问基类中的方法时,应该使用什么设计模式?

java - 这是聚合的正确用法吗

python - 为什么我的 numpy 构造忽略元组解构?

python - 套接字火箭(iOS): How to identify whom user are chatting with another?

python - Django try/except on DoesNotExist 仍然抛出它