Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple instantiations of python classes

Tags:

python

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>>
like image 380
nlper Avatar asked Dec 12 '22 10:12

nlper


2 Answers

f is a method, so you need to call it. i.e. x.f()

It's no different than if you define a function without the class:

def f():
    return 'something'

If you just refer to f, you'll get the function itself

print f

yields <function f at 0xdcc2a8>, while

print f()

yields "something".

like image 182
Joe Kington Avatar answered Jan 03 '23 22:01

Joe Kington


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:

>>> 1
1

If it is an assignment, then nothing will be printed:

>>> a = 1

But, watch this:

>>> a = 1
>>> a
1

Ok, so in your code above:

>>> 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> 

So, the value of x is an instance of MyClass located at a spot in memory.

>>> x.i
12345

The value of x.i is 12345, so it will be printed as above.

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

The value of f is a method of x (that's what it means to have def in front of something, it is a method). Now, since it is a method, let's call it by adding the () after it:

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

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 print function:

>>> print(x.f()) # this may be print x.f() (note the number of parens)
                 # based on different versions of Python. 
hello world
like image 41
cwallenpoole Avatar answered Jan 03 '23 22:01

cwallenpoole