简体   繁体   中英

Dealing with class inheritance in python

Can someone explain why I'm getting the error:

global name 'helloWorld' is not defined

when executing the following:

class A:
    def helloWorld():
        print 'hello world'

class B(A):
    def displayHelloWorld(self):
        helloWorld()

class Main:
     def main:
        b = B()
        b.displayHelloWorld()

I'm used to java where class B would obviously have a copy of class A's method "helloWorld" and thus this code would run fine when executing main. This however appears to think class B doesn't have any method called "helloWorld"

Missing the self before the helloWorld(). The self keyword means that this an instance function or variable. When class B inherits class A, all the functions in class A can now be accessed with the self.classAfunction() as if they were implemented in class B.

class A():
    def helloWorld(self): # <= missing a self here too
        print 'hello world'

class B(A):
    def displayHelloWorld(self):
        self.helloWorld()

class Main():
     def main(self):
        b = B()
        b.displayHelloWorld()

You need to indicate that the method is from that class ( self. ):

class B(A):
    def displayHelloWorld(self):
        self.helloWorld()

Python differs in this from Java. You have to specify this explicitly in Python whereas Java accepts implicitly as well.

I don't know what is the version of python used in this example but it seems that syntax looks like python3. (except print statement which looks like python2.x)

Lets suppose that this is python3

I would say that helloWorld is class method of class A and It should be called as class attribute. As soon as this function is in class namespace It can be accessed outside this class only using owner class.

A.helloWorld()

or

B.helloWorld()

or

self.__class__.helloWorld()

You can't call it as bound method in this case because self argument will be passed and as soon as your function doesn't expect it it will fail.

there is possibility that helloWorld is method of A and self parameter is just missed

in this case this method can be called as follow:

self.helloWorld()

or

A.helloWorld(self)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM