gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:48:20 25 4
gpt4 key购买 nike

我想问一下如何在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”。我仍在学习如何从这个案例中获取变量。

我在互联网上搜索过,但还是不明白。谢谢你的帮助

最佳答案

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

在 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)

关于python - 如何从python中的继承类函数加载变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25236800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com