2015-05-20 22 views
0

这可能是微不足道的,但搜索这个时候我不分辨率:Python不显示类的打印报表,结果

我有以下简单的类:

class Celcius: 
    def __init__(self, temperature=0): 
     self.temperature = temperature 

    def to_fahrenheit(self): 
     return (self.temperature*1.8) + 32 

    def get_temperature(self): 
     print "getting temp" 
     return self._temperature 

    def set_temperature(self, value): 
     if value < -273: 
      raise ValueError("dayum u trippin' fool") 
     print "setting temp" 
     self._temperature = value 

    temperature = property(get_temperature, set_temperature) 

c = Celcius() 

当我运行这个在Sublime Text 3中(通过点击cmd + B)控制台不会打印任何东西。我应该看到:

setting temp 

如果我添加以下到脚本的末尾:预期

print "banana" 
print "apple" 

两行打印。

如果我从终端(使用python -u或python)运行上面的python脚本,结果是完全一样的。我想我错过了一些非常愚蠢的事情。谢谢

回答

8

这不起作用,因为你写

class Celcius: 
    ... 

而使用新式课程的特点。要使用属性,您需要继承对象:

class Celcius(object): 
    ... 

是否有用。

参考:Descriptor Howto,报价:注意,描述符仅调用新的样式对象或类(一类新的风格,如果它从对象或类型继承)

+0

啊,那工作!谢谢。所以我应该总是从'object'固有才是安全的? – luffe

+0

斑点。 =) – khelwood

+1

@luffe:阅读词汇表中的[“新风格类”](https://docs.python.org/2/glossary.html#term-new-style-class)。在Python 3中,你总是有新式的类,所以你的代码会在没有修改的情况下运行。 – Matthias

-1

您根本没有拨打set_temperature(self, value)方法。

此行

self.temperature = temperature 

__init__()方法(这是由c = Celcius()调用)只设置直接self.temperature,而不调用制定者。

显而易见的解决方案是从重写的init()方法:

def __init__(self, temperature=0): 
    self.temperature = temperature 

到:

def __init__(self, temperature=0): 
    self.set_temperature(temperature) 
+0

但是,如果我运行上面的代码(有在www.repl.it的Python 3解释器上打印“setting temp”...? – luffe

+2

有一个'temperature' *属性*,它在分配给它时调用'set_temperature'。 –

+0

你是对的,我知道属性,但我错过了那条线。谢谢。 – geckon