从子类中的父类访问属性

从子类中的父类访问属性

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

问题描述

当我通过子类从父类访问属性时,所有工作正常:

 
a = 1
b = 2

B类(A):
c = 3

d = B.a + B.b +但是如果我试图从父类中访问一个属性,并且在属性中包含了一个属性,那么我们可以使用这个属性来创建一个属性:Bc
print d


$ b

  class A():
a = 1
b = 2

B类(A):
c = 3
d = a + b + c
打印d
/ pre>

我收到错误:名称'a'未定义



假设我有很多方程,如d = a + b + c(但更复杂),我不能编辑它们 - 我必须在类B中调用a不是self.a或something.a。但我可以,在方程式之前,做A.a = a。但它不是最聪明的方式手动重新加载所有变量。我想绕过它使用继承。是可能还是我应该做所有手动?

解决方案

这可能是错误的,但你确定你没有想要这个吗?

  class A(object):
def __init __(self):
self。 a = 1
self.b = 2


class B(A):
def __init __(self):
super .__ init __()
self.c = 3

@property
def d(self):
return self.a + self.b + self.c

BB = B()
print BB.d

,as jonrsharpe指出:

  A类():
a = 1
b = 2

B类(A):
c = 3
d = A.a + A.b + c

打印Bd


When I access an attribute from the parent class via the child class like this all works fine:

class A():
    a=1
    b=2

class B(A):
    c=3

d=B.a+B.b+B.c
print d

But if I try to access an attribute from the parent class inside the child class like this, it doesn't work:

class A():
    a=1
    b=2

class B(A):
    c=3
    d=a+b+c
    print d

I receive the error: name 'a' is not defined

Let assume that I have many equation like d=a+b+c (but more complicated) and I can't edit them - I have to call in class B "a" as "a", not "self.a" or "something.a". But I can, before equations, do A.a=a. But it is not the smartest way to reload all variables manually. I want to bypass it using inheritance. Is it possible or i should do all manually? Or maybe it is 3th route in this code?

解决方案

I may be wrong on this, but are you sure you don't want rather this?

class A(object):
    def __init__(self):
        self.a = 1
        self.b = 2


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

    @property
    def d(self):
        return self.a + self.b + self.c

BB = B()
print BB.d

or, as jonrsharpe pointed out:

class A():
    a=1
    b=2

class B(A):
    c=3
    d=A.a+A.b+c

print B.d

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

09-01 19:43