【问题标题】:How to make Multiply function inside a Class Python如何在 Python 类中创建乘法函数
【发布时间】:2018-12-31 04:25:39
【问题描述】:

我在代码或功能区域中缺少什么?有什么建议吗?如果有人知道一个学习面向对象编程的好地方,请告诉我,谢谢。

class Square():
def __init__(self,height=0,width=0):
    self._height = height
    self._width = width

@property
def height(self):
    return self._height

@property
def width(self):
    return self._width

def area(self):
    return height * width

@height.setter
def set_height(self,new_height):
    self._height = new_height

@width.setter
def set_width(self,new_width):
    self._width = new_width

【问题讨论】:

  • 与您的主要问题无关:如果您没有在 property 方法中进行任何验证或计算,您可能应该取消它们并直接访问 heightwidth 变量.另一方面,area 可能是一个很好的候选 property,如果您不想显式调用它。
  • @blckknght 我得到的答案是 <__main__.square object at>>
  • 您要么需要将其设为属性,要么调用它。你似乎两者都没有。
  • 如果答案是正确的(如给定的),您应该勾选正确的复选标记。

标签: python class oop object properties


【解决方案1】:

您的区域函数中缺少self.heightself.width

你的 setter 的名字也应该和你的 getter 相匹配。像这样的东西。

class Square():
    def __init__(self, height=0, width=0):
        self._height = height
        self._width = width

    @property
    def height(self):
        return self._height

    @property
    def width(self):
        return self._width

    def area(self):
        return self.height * self.width

    @height.setter
    def height(self, new_height):
        self._height = new_height

    @width.setter
    def width(self, new_width):
        self._width = new_width

然后你必须实例化这个类,并使用返回的对象来访问它的属性和方法,就像这样。

s = Square(2, 4)
s.area()
s.height = 6

【讨论】:

  • 谢谢@joarobot,但我试过了,它没有给出任何答案(>)
  • @Encode.to.code 我已经用如何实例化类的示例更新了答案。学习一门新语言有很多不同的方法,具体取决于哪种学习方法最适合您。做这样的练习是一种方法,另一种我发现特别有用的方法是阅读 O'Reilly Introduction to Python 这本书。但是,如果您不想投资一本书,互联网上充满了有用的资源。
  • 你想发布你得到的错误@Encode.to.code
  • 不是错误,这是输出 main.Square.area> @joerobot
猜你喜欢
相关资源
最近更新 更多
热门标签