Python没有在类中显示print语句的结果

luf*_*ffe 1 python python-2.7

这可能是微不足道的,但在搜索时我没有得到解决方案:

我有以下简单的类:

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()
Run Code Online (Sandbox Code Playgroud)

当我在Sublime Text 3(通过点击cmd + B)中运行它时,控制台不会打印任何内容.我应该看到:

setting temp
Run Code Online (Sandbox Code Playgroud)

如果我将以下内容添加到脚本的末尾:

print "banana"
print "apple"
Run Code Online (Sandbox Code Playgroud)

这两行都按预期打印.

如果我从终端运行上面的python脚本(使用python -u,或者只是python),结果完全相同.我想我错过了一些非常愚蠢的东西.谢谢

Blu*_*orn 10

这不起作用,因为你写了

class Celcius:
    ...
Run Code Online (Sandbox Code Playgroud)

同时使用新式课程的功能.要使用属性,您需要从对象继承:

class Celcius(object):
    ...
Run Code Online (Sandbox Code Playgroud)

诀窍.

参考:描述符Howto,引用:请注意,仅为新样式对象或类调用描述符(如果类从对象或类型继承,则该类是新样式)