【问题标题】:Python does not show result of print statements in class [duplicate]Python不显示类中打印语句的结果[重复]
【发布时间】:2015-08-01 13:48:53
【问题描述】:

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

我有以下简单的类:

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 脚本(使用 python -u,或者只是 python),结果是完全一样的。我想我错过了一些非常愚蠢的东西。谢谢

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    这不起作用,因为你写了

    class Celcius:
        ...
    

    同时使用新式类的特性。要使用属性,您需要从对象继承:

    class Celcius(object):
        ...
    

    成功了。

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

    【讨论】:

    • 啊,成功了!谢谢你。所以为了安全起见,我应该始终来自object
    • @luffe:阅读词汇表中的"new-style class"。在 Python 3 中,您总是有新样式的类,因此您的代码将在那里运行而无需修改。
    【解决方案2】:

    您根本没有调用set_temperature(self, value) 方法。

    这一行

    self.temperature = temperature
    

    在您的__init__() 方法(由c = Celcius() 调用)中直接设置self.temperature,而不调用setter。

    显而易见的解决方案是从以下位置重写您的 init() 方法:

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

    到:

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

    【讨论】:

    • 但是如果我在 www.repl.it 的 Python 3 解释器上运行上面的代码(在 print 语句周围加上括号),它会打印“setting temp”...?
    • 有一个temperatureproperty,分配给它的时候调用set_temperature
    • 你是对的,我知道属性,但我错过了那条线。谢谢。
    • @luffe:在 Python 3 中它将使用该属性,因为所谓的“新样式类”是默认存在的。在 Python 2 中,您必须将 object 设为基类。
    最近更新 更多