python类的简单实例

问题描述:

你能解释为什么'hello world'不被返回到下面吗?我需要修改什么才能在被调用时正确表达?谢谢。python类的简单实例

>>> class MyClass: 
...  i=12345 
...  def f(self): 
...   return 'hello world' 
...  
>>> x=MyClass() 
>>> x.i 
12345 
>>> x.f 
<bound method MyClass.f of <__main__.MyClass instance at 0x060100F8>> 

当在REPL(或Python控制台或其它)中时,总是会打印最后一条语句返回的值。如果它仅仅是一个值的值将被打印出来:

>>> 1 
1 

如果它是一个任务,然后什么都不会被打印:

>>> a = 1 

不过,看这个:

>>> a = 1 
>>> a 
1 

好的,在上面的代码中:

>>> x=MyClass() 
>>> x # I'm adding this :-). The number below may be different, it refers to a 
     # position in memory which is occupied by the variable x 
<__main__.MyClass instance at 0x060100F8> 

因此,x的值是MyClass位于内存中的一个实例。

>>> x.i 
12345 

x.i的值是12345,因此它将如上打印。

>>> x.f 
<bound method MyClass.f of <__main__.MyClass instance at 0x060100F8>> 

F值是x的方法(这就是它意味着有def在前面的东西,它是一种方法)。现在,因为它是一种方法,让我们加入后的()叫它:

>>> x.f() 
'hello world' 

在变量x的MyClass的实例用f方法返回的值是“世界你好”!可是等等!有引号。我们通过使用print功能摆脱它们:

>>> print(x.f()) # this may be print x.f() (note the number of parens) 
       # based on different versions of Python. 
hello world 
+1

彻底的答案是一个很好的答案,值得花时间。 – cwallenpoole

+0

非常感谢,@cwallenpoole!这是一个彻底的答复。我非常感谢你的明确解释。 – nlper

+1

@niper - 顺便说一下,cwallenpoole的回答(在我看来)比我的回答更清晰,更彻底。不要因为我碰巧早点得到更多选票而感到需要标记我的权利!标记哪一个最能帮助你“接受”。 :) –

f是一种方法,所以你需要调用它。即x.f()

这是没有什么不同,如果你定义一个函数没有类:

def f(): 
    return 'something' 

如果你只是参考f,你会得到函数本身

print f 

产量<function f at 0xdcc2a8>,同时

print f() 

收益率"something"

+0

非常感谢@Joe Kington!我正在阅读一个教程,并没有提到。再次感谢。 – nlper