Can you please explain why ‘hello world’ isn’t returned below? What do I need to modify for it to be expressed properly when called? Thanks.
>>> 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>>
When inside the REPL (or the Python console, or whatever) the value returned by the last statement will always be printed. If it is just a value the value will be printed:
If it is an assignment, then nothing will be printed:
But, watch this:
Ok, so in your code above:
So, the value of x is an instance of MyClass located at a spot in memory.
The value of x.i is 12345, so it will be printed as above.
The value of f is a method of x (that’s what it means to have
defin front of something, it is a method). Now, since it is a method, let’s call it by adding the()after it:The value returned by f method on the MyClass instance in the variable x is ‘hello world’! But wait! There are quotes. Let’s get rid of them by using the
printfunction: