2

This is a sample code that i found from one of the python class tutorial.

class MyClass:
    i = 12345
    def f(self):
        return 'hello world'

print MyClass.f
print MyClass.i

Once i run this, i am expecting the output result of "hello world" and "12345". But instead i am getting this

>>> 
<unbound method MyClass.f>
12345
>>> 

why is it not giving me 'hello world'? How do i change my code so that it will print out "hello world"? P.S i have no clue about python classes and methods and just started learning.

2 Answers 2

7

Create an instance of MyClass first.

test = MyClass()
print test.f()
print MyClass.i

You don't need to create an instance of MyClass for i, because it is a class member, not an instance member.

Sign up to request clarification or add additional context in comments.

1 Comment

This is right, but you might also want to mention that OP needs to call the method as well, otherwise python will just print out the information about the method rather than running it's code.
1

Always a function is called by its name, which is represented by (). So use MyClass.f()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.