简体   繁体   中英

Issue in calling the base class methods

I am newbie in Python.I know this question is useless.But I am frustrated with my issue.I have 2 methods defined in my base class Animals .When I try to call the base methods in my inherited classes it shows these error: NameError: name 'display_name' is not defined

class Animals():
    def display_name(self):
        print ('Name is Mr.X')        
    def display_age(self):
        print('Age is 25')    
class Name(Animals):
    display_name(self)
class Age(Animals):
    display_age(self)

n=Name()
a=Age()
n.display_name()
a.display_age()

You need to refer to the display_name function with a self prefix instead of passing self as an argument.

Also, as noted by Antimony, you need to call the display_name from within a function that is associated with an instance of the class (inside a function that accepts the self argument).

Code that appears outside a method function but inside a class is associated with the whole class, not with any particular instance of that class - using the self variable in this context has no meaning - if you create multiple objects from the class which one does it refer to?

class Animals():
    def display_name(self):
        print ('Name is Mr.X')

    def display_age(self):
        print('Age is 25')    

class Name(Animals):
    def call_display_name(self):
        self.display_name()

class Age(Animals):
    def call_display_name(self):
        self.display_age()

Name().call_display_name()

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