Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中使用属性方法计算面积_Python_Python 3.x - Fatal编程技术网

在Python中使用属性方法计算面积

在Python中使用属性方法计算面积,python,python-3.x,Python,Python 3.x,我正在使用Python3,我创建了以下类来获取并返回矩形的高度和宽度: lass rectangle: def __init__(self): self.height = 0 self.width = 0 def set_size(self, size): self.width, self.height = size def get_size(self, size): return self.width, s

我正在使用Python3,我创建了以下类来获取并返回矩形的高度和宽度:

lass rectangle:
    def __init__(self):
        self.height = 0
        self.width = 0
    def set_size(self, size):
        self.width, self.height = size
    def get_size(self, size):
        return self.width, self.height

    size = property(get_size, set_size)

但是,我还想添加另一个属性
area
,该属性使用property函数仅返回矩形的面积。因此,我尝试了以下方法:

class rectangle:
    def __init__(self):
        self.height = 0
        self.width = 0
    def set_size(self, size):
        self.width, self.height = size
    def get_size(self, size):
        return self.width, self.height
    def area(self, size):
        self.width * self.height = area


    size = property(get_size, set_size,area)

r = rectangle()
r.width = 6
r.height = 10
r.size = 7, 10
print(r.area)
但是,当我在控制台中尝试测试时,会出现以下错误:

self.width * self.height = area
    ^
SyntaxError: cannot assign to operator

如果您能解释一下,我将不胜感激。谢谢

您的LHS值应为RHS值,反之亦然:


area=self.width*self.height

您混淆了分配值

class rectangle:
    def __init__(self):
        self.height = 0
        self.width = 0
    def set_size(self, size):
        self.width, self.height = size
    def get_size(self, size):
        return self.width, self.height
    @property
    def area(self):
        area = self.width * self.height 
        return area
    
    size = property(get_size, set_size,area)

r = rectangle()
r.width = 6
r.height = 10
r.size = 7, 10
print(r.area)

self.area=self.width*self.height
?或
返回self.width*self.height