如何在python中从继承的类函数加载变量

时间:2014-08-11 06:08:46

标签: python oop

我想问一下如何在python

中从继承的类函数加载变量

这是第一堂课的例子

class Shape:
        def __init__(self,x,y):
            self.x = x
            self.y = y
        description = "This shape has not been described yet"
        author = "Nobody has claimed to make this shape yet"
        def area(self):
            return self.x * self.y
        def perimeter(self):
            return 2 * self.x + 2 * self.y
        def describe(self,text):
            self.description = text
        def authorName(self,text):
            self.author = text
        def scaleSize(self,scale):
            self.x = self.x * scale
            self.y = self.y * scale

并且,这是第二类

class Square(Shape):
    def __init__(self,x):
        self.x = x
        self.y = x

在上面列出的两个类中,我想从'Square'中取变量'x'。 我还在学习如何从这个案例中取一个变量。

我搜索了互联网,但仍然没有得到它。 谢谢你的帮助

2 个答案:

答案 0 :(得分:3)

执行此操作的一种方法是调用基类构造函数。

在Python 3中:

class Square(Shape):
    def __init__(self,x):
        super().__init__(x, x)

在Python 2中(也适用于3):

class Square(Shape):
    def __init__(self,x):
        Shape.__init__(self, x, x)

答案 1 :(得分:1)

首先,无论您遇到什么问题,我认为您希望在Miguel Prz的答案中进行更改,并使用super将值传递给基类,而不是直接在{{{}创建属性1}}。 (而且我认为这就是你所要求的 - 它有效地将变量Squarex类中取出并将其放在它所属的基类Square中。但我猜不是。)无论如何,让我们忽略那一部分再做一次猜测。

  

我想把变量' x'来自' Square'

也许这意味着您想要从Shape的实例访问变量x的值?如果是这样,那就像大多数其他语言一样只是#34; dot语法":

Square

在你做的地方并不重要,即使在一些不知道它处理方形的函数中,代码也是一样的:>>> myshape = Square(10) >>> print(myshape.x) 10 。例如:

whatever.x