类函数不返回正确的值

时间:2017-09-05 12:37:37

标签: python class methods

这是我的代码:

library(ggplot2)

plot_it <- function(){
  a <- rnorm(1000, mean = 50, sd = 10)
  print(summary(a)) 
  p <- ggplot()+geom_histogram(aes(x=a), bins=40)
  print(p)
}

repeat {
  startTime <- Sys.time()
  plot_it()
  sleepTime <- startTime - Sys.time()+ 6
  if (sleepTime > 0)
    Sys.sleep(sleepTime)
}

对于输入class Rectangle(object): def __init__(self, height, width): self.height = height self.width = width def __str__(self): return '{} x {} = {}'.format(self.height, self.width, self.area) def area(self): self.area=self.height*self.width return self.area def primarySchool(height, width): return str(Rectangle(height, width)) height=7,输出为

width=4

而不是>>> primarySchool(7, 4): 7 x 4 = <bound method _runjcbjp.<locals>.Rectangle.area of <__main__._runjcbjp.<locals>.Rectangle object at 0x2b482cd637f0>>

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

area班级中,print(self.area)成员被定义为方法。 因此,<...>将为您提供该方法对象的表示,即area事物。

你想要的是return '{} x {} = {}'.format(self.height, self.width, self.area()) 方法的结果,而不是方法本身。 因此,您需要通过在其名称后面加上括号来调用方法。

您的代码应为:

area

另外,请注意不要在方法中重新分配相同的名称。 在self.area = self.height * self.width 方法中,您可以写下:

instance.area()

因此,在第一次调用area之后,sudo apt-get install r-base 成员将被覆盖,从函数到数字。 因此后续调用将失败,例如&#34; Int对​​象不可调用&#34;。

答案 1 :(得分:2)

area是您的类的一种方法,因此您必须调用它来获取返回值(而不是方法本身)。

但鉴于您在方法中分配给self.area,您似乎希望将其视为“缓存”property(无需显式调用即可访问):

class Rectangle(object):
    def __init__(self, height, width):
        self.height = height
        self.width = width

    def __str__(self):
        return '{} x {} = {}'.format(self.height, self.width, self.area)

    @property
    def area(self):   # cached version
        try:
            return self._area
        except AttributeError:
            self._area=self.height*self.width
        return self._area


def primarySchool(height, width):
    return str(Rectangle(height, width))

primarySchool(7, 4)
# '7 x 4 = 28'

或者作为未缓存的版本:

class Rectangle(object):
    def __init__(self, height, width):
        self.height = height
        self.width = width

    def __str__(self):
        return '{} x {} = {}'.format(self.height, self.width, self.area)

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

或者只是在__init__中计算并将其设置为属性:

class Rectangle(object):
    def __init__(self, height, width):
        self.height = height
        self.width = width
        self.area = height * width

    def __str__(self):
        return '{} x {} = {}'.format(self.height, self.width, self.area)

答案 2 :(得分:1)

您正试图同时拥有一个名为&#34; area&#34;的功能和属性。

为什么不简单:

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

致电:

self.area()
相关问题