为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

撒科打诨 2022-10-05 18:19:51
class A():    def __init__(self, a, b):        self.a = a        self.b = bclass B(A):    def __init__(self, c):        self.c = cclass C(A):    def __init__(self, d):        self.d = dtemp = A("japan", "Germany")childtemp1 = B("California")childtemp2 = C("Delhi")有时我将 B 类和 C 类用于两个不同的目的,但它们都有一些相同的公共变量,这些变量存在于 A 类中,并且 A 类已经实例化。我在一些更多不同的类中使用这个类 B 和 C,我想同时使用类(A 和 B)和类(A 和 C)的变量。
查看完整描述

2 回答

?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

如果你想访问a, b, cusingchildtemp1你需要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


查看完整回答
反对 回复 2022-10-05
?
忽然笑

TA贡献1806条经验 获得超5个赞

这个例子可以帮助你理解


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


查看完整回答
反对 回复 2022-10-05
  • 2 回答
  • 0 关注
  • 179 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号