python类的简单实例化

python类的简单实例化,python,Python,你能解释一下为什么下面没有返回“hello world”吗?我需要修改什么才能在调用时正确表达它?谢谢 >>> class MyClass: ... i=12345 ... def f(self): ... return 'hello world' ... >>> x=MyClass() >>> x.i 12345 >>> x.f <bound method MyClass.f

你能解释一下为什么下面没有返回“hello world”吗?我需要修改什么才能在调用时正确表达它?谢谢

>>> 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>>
>>类MyClass:
...     i=12345
...     def f(自我):
...         返回“你好,世界”
...     
>>>x=MyClass()
>>>x.i
12345
>>>x.f

f
是一个方法,因此需要调用它。i、 e.
x.f()

这与定义没有类的函数没有什么不同:

def f():
    return 'something'
如果只参考
f
,您将获得函数本身

print f
产生
,而

print f()
当在REPL(或Python控制台,或其他)中时,将始终打印最后一条语句返回的值,从而生成“something”

。如果只是一个值,将打印该值:

>>> 1
1
>>> a = 1
如果是作业,则不会打印任何内容:

>>> 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.i的值为12345,因此将按上述方式打印

>>> x.f
<bound method MyClass.f of <__main__.MyClass instance at 0x060100F8>>
变量x中MyClass实例上的f方法返回的值是“hello world”!但是等等!这里有引语。让我们使用
print
功能来消除它们:

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

非常感谢乔·金顿!我正在学习一个教程,但没有提到。再次感谢。非常感谢,@cwallenpole!这是一个如此彻底的答复。我真的很感激你的清楚解释。@niper-顺便说一句,cwallenpole的回答(在我看来)比我的回答更清楚、更彻底。不要仅仅因为我碰巧在早些时候获得了更多的选票,就觉得有必要给我的选票打分!将对您帮助最大的一个标记为“已接受”。)谢谢,乔·金顿。你是一个非常公正的人。我希望这种媒介能提供不止一个正确答案。