Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python不在类中显示print语句的结果_Python_Python 2.7 - Fatal编程技术网

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

Python不在类中显示print语句的结果,python,python-2.7,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 "gettin

这可能很琐碎,但我在搜索时没有得到解决:

我有以下简单的类:

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()
如果在脚本末尾添加以下内容:

print "banana"
print "apple"
两行都按预期打印


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

您根本没有调用
设置温度(self,value)
方法

这条线

self.temperature = temperature
\uuuu init\uuuu()
方法(由
c=Celcius()
调用)中,只需直接设置
自身温度,而无需调用setter

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

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


您根本没有调用
设置温度(self,value)
方法

这条线

self.temperature = temperature
\uuuu init\uuuu()
方法(由
c=Celcius()
调用)中,只需直接设置
自身温度,而无需调用setter

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

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


这不起作用,因为你写了

class Celcius:
    ...
同时使用新样式类的功能。要使用属性,您需要从对象继承:

class Celcius(object):
    ...
这就是诀窍


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

这不起作用,因为您编写了

class Celcius:
    ...
同时使用新样式类的功能。要使用属性,您需要从对象继承:

class Celcius(object):
    ...
这就是诀窍


引用:,引号:注意,描述符只对新样式的对象或类调用(如果类继承自对象或类型,则为新样式)

但是如果我在www.repl上运行上述代码(在print语句周围加括号)。这是Python 3解释器,它会打印“setting temp”…?有一个
temperature
属性,分配给它时,它会调用
set\u temperature
。你是对的,我知道属性,但我错过了那一行。谢谢。@luffe:在Python 3中,它将使用该属性,因为所谓的“新样式类”是默认的。在Python 2中,必须将
对象
作为基类。但是如果我在www.repl上运行上面的代码(在print语句周围加括号)。它是Python 3解释器,它会打印“setting temp”…?有一个
temperature
属性,它在分配给它时调用
set_temperature
。你是对的,我知道房地产,但我错过了那一行。谢谢。@luffe:在Python 3中,它将使用该属性,因为所谓的“新样式类”是默认的。在Python2中,必须将
对象
作为基类。啊,这很有效!非常感谢。因此,为了安全起见,我应该始终从
对象
中提取信息?@luffe:阅读词汇表中的相关内容。在Python3中,您总是有新样式的类,因此您的代码将在那里运行,而无需修改。啊,这很有效!非常感谢。因此,为了安全起见,我应该始终从
对象
中提取信息?@luffe:阅读词汇表中的相关内容。在Python3中,您总是有新样式的类,因此您的代码将在那里运行而无需修改。