鱼C论坛

 找回密码
 立即注册
查看: 5863|回复: 3

[已解决]python类实例化对象,计算结果不对

[复制链接]
发表于 2016-8-24 20:10:07 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
class Rectangle:
        def __init__(self,x,y):
                self.x=x
                self.y=y
        def getperi(self):
                return (self.x+self.y)*2
        def getarea(self):
                return self.x*self.y

       
>>> rect=Rectangle(3,4)
>>> rect.getarea
<bound method Rectangle.getarea of <__main__.Rectangle object at 0x00000000031F55F8>>
>>>
最佳答案
2023-12-5 16:31:14
中英文泡椒 发表于 2023-12-05 16:30
@FishC_GPT
class Rectangle:
        def __init_ ...

问题是您调用了`rect.getarea`,但没有加上`()`来调用它。在Python中,函数调用需要添加小括号。所以您需要使用`rect.getarea()`来调用该方法。以下是修正后的代码:
  1. class Rectangle:
  2.     def __init__(self, x, y):
  3.         self.x = x
  4.         self.y = y
  5.     def getperi(self):
  6.         return (self.x + self.y) * 2
  7.     def getarea(self):
  8.         return self.x * self.y
  9. rect = Rectangle(3, 4)
  10. print(rect.getarea())  # 调用getarea方法,并打印结果
复制代码

运行上述代码,将会输出矩形的面积为12。

以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-8-24 21:26:27 | 显示全部楼层
rect.getarea()
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-12-5 16:30:57 | 显示全部楼层
@FishC_GPT
class Rectangle:
        def __init__(self,x,y):
                self.x=x
                self.y=y
        def getperi(self):
                return (self.x+self.y)*2
        def getarea(self):
                return self.x*self.y

      
>>> rect=Rectangle(3,4)
>>> rect.getarea
<bound method Rectangle.getarea of <__main__.Rectangle object at 0x00000000031F55F8>>
>>>
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-12-5 16:31:14 | 显示全部楼层    本楼为最佳答案   
中英文泡椒 发表于 2023-12-05 16:30
@FishC_GPT
class Rectangle:
        def __init_ ...

问题是您调用了`rect.getarea`,但没有加上`()`来调用它。在Python中,函数调用需要添加小括号。所以您需要使用`rect.getarea()`来调用该方法。以下是修正后的代码:
  1. class Rectangle:
  2.     def __init__(self, x, y):
  3.         self.x = x
  4.         self.y = y
  5.     def getperi(self):
  6.         return (self.x + self.y) * 2
  7.     def getarea(self):
  8.         return self.x * self.y
  9. rect = Rectangle(3, 4)
  10. print(rect.getarea())  # 调用getarea方法,并打印结果
复制代码

运行上述代码,将会输出矩形的面积为12。

以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-21 15:14

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表