Chris Headleand
Chris Headleand

Reputation: 6193

Printing from within an object

I have tried to get one python object to inherit another. I wrote a script to test things were working (see below). However, when I try to access the methods within those objects nothing gets printed and I cant understand why. Could anyone point me in the right direction?

print("hello world")

class parent():
    def helloWorld(self, ):
        print("hello World1")

class child(parent):
    def helloWorld2(self, ):
        print("hello World2")

parentOBJ = parent()
childOBJ = child()


parentOBJ.helloWorld
childOBJ.helloWorld
childOBJ.helloWorld2

The code above prints the first "hello world" statement but nothing after.

Upvotes: 0

Views: 39

Answers (2)

sshashank124
sshashank124

Reputation: 32189

You are simply referencing the methods and not actually making a call to them.

Do this instead:

parentOBJ.helloWorld()
childOBJ.helloWorld()
childOBJ.helloWorld2()

When you make a call to a function, you have to do method_name(arguments).

So if I have a method called def hello(a, b):, I will actually need to pass the arguments to the function as well, something as follows: hello('hello', 'world').

Example

>>> def hello(): 
...     print 'hello' 
...  
>>> hello
<function hello at 0x2340bc>
>>> hello()
hello

Hope that helps.

Upvotes: 3

msvalkon
msvalkon

Reputation: 12077

You're not calling the methods. Add () after each method when you want to call them. Otherwise your interpreter will only return the type of the object.

parentOBJ.helloWorld()
childOBJ.helloWorld()
childOBJ.helloWorld2()

However you'll have to fix your class definitions as well:

class parent(object): # All classes should inherit from the object-class
    def helloWorld(self): # unless you have other arguments besides self, remove the comma.
        print("hello World1")

class child(parent):
    def helloWorld2(self):
        print("hello World2")

Example:

>>> parentOBJ = parent()
>>> childOBJ = child()
>>> parentOBJ.helloWorld()
hello World1
>>> childOBJ.helloWorld()
hello World1
>>> childOBJ.helloWorld2()
hello World2

Upvotes: 4

Related Questions