python类变量继承_Python从父类继承变量

Sorry if I don't explain it that well but I'll try my best:

So I want to inherit the variables from the Parent class, but I don't want to pass them again when creating an instance of the Child class because I think that is redundant. I just want to use the eye color from the Parent for example. See the example code below for what I mean

This is what works:

class Parent:

def __init__(self, eye_color, length):

self.eye_color = str(eye_color)

self.length = length

class Child(Parent):

def __init__(self, gender, eye_color, length):

super().__init__(eye_color, length)

self.gender = str(gender)

x = Parent("Blue", 2)

y = Child("Men", "Blue", 2)

print(x.eye_color, x.length)

print(y.gender, x.length)

This is what I somehow want:

class Parent:

def __init__(self, eye_color, length):

self.eye_color = str(eye_color)

self.length = length

class Child(Parent):

def __init__(self, gender):

super().__init__(eye_color, length)

self.gender = str(gender)

x = Parent("Blue", 2)

y = Child("Men")

print(x.length, x.eye_color)

print(y.gender, x.length)

解决方案

You could try passing a Parent instance to the Child initializer...That's probably the closest you'll get.

class Parent:

def __init__(self, eye_color, length):

self.eye_color = str(eye_color)

self.length = length

class Child(Parent):

def __init__(self, gender, parent):

super().__init__(parent.eye_color, parent.length)

self.gender = str(gender)

x = Parent("Blue", 2)

y = Child("Men", x)

print(x.length, x.eye_color)

print(y.gender, x.length)

Another thing you could do is hold a last_parent variable:

global last_parent

class Parent:

def __init__(self, eye_color, length):

self.eye_color = str(eye_color)

self.length = length

last_parent = self

class Child(Parent):

def __init__(self, gender):

super().__init__(last_parent.eye_color, last_parent.length)

self.gender = str(gender)

x = Parent("Blue", 2)

y = Child("Men")

print(x.length, x.eye_color)

print(y.gender, x.length)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值