2015-05-20 72 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