从子类实例访问父类实例属性? [英] Access parent class instance attribute from child class instance?

查看:65
本文介绍了从子类实例访问父类实例属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码示例中,如何从子访问 myvar:

How to access "myvar" from "child" in this code example:

class Parent():
    def __init__(self):
        self.myvar = 1

class Child(Parent):
    def __init__(self):
        Parent.__init__(self)

        # this won't work
        Parent.myvar

child = Child()


推荐答案

父级是一个类-蓝图不是它的实例,OOPS中的
用于访问它需要的对象的属性相同的实例,
在这里,自我/孩子是实例,而父母/孩子是班级...

Parent is a class - blue print not an instance of it, in OOPS to access attributes of an object it requires instance of the same, Here self/child is instance while Parent/Child are classes...

请参阅以下答案,可以澄清您的疑问。 / p>

see the answer below, may clarify your doubts.

class Parent():
    def __init__(self):
        self.myvar = 1

class Child(Parent):
    def __init__(self):
        Parent.__init__(self)

        # here you can access myvar like below.
        print self.myvar

child = Child()
print child.myvar

这篇关于从子类实例访问父类实例属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆