Python Forum

Full Version: Listing All Methods Of Associated With A Class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello

I wanted to ask whether it was possible to list all the methods associated with a Class for example:-

I have created the following class:-

class Human():

    
    def __init__(self, sex, eyecolor, height, yearborn):
     
        self.sex = sex
        self.eyecolor = eyecolor
        self.height = height
        self.yearborn = yearborn
        
        print("Object", self.sex, self.eyecolor, self.height, self.yearborn, "Has been created")
        
    
    def age(self):
        currentdate = date.today()
        a = currentdate.year - self.yearborn
        return a
    
    def display(self):
        print(self.sex)
        print(self.eyecolor)
        print(self.height)
        print(self.yearborn)
        
In the above class I have created I have 2 x methods age() and display().

My question is this: is there any Python code that allows me to enter the name of the class and the output are all the methods associated with that class?

Thank you.
import inspect


class Human:

    def __init__(self, sex, eyecolor, height, yearborn):

        self.sex = sex
        self.eyecolor = eyecolor
        self.height = height
        self.yearborn = yearborn

        print("Object", self.sex, self.eyecolor,
              self.height, self.yearborn, "Has been created")

    def age(self):
        currentdate = date.today()
        a = currentdate.year - self.yearborn
        return a

    def display(self):
        print(self.sex)
        print(self.eyecolor)
        print(self.height)
        print(self.yearborn)

print(inspect.getmembers(Human, inspect.isfunction))
print(inspect.getmembers(Human(1, 2, 3, 4), inspect.ismethod))
Output:
[('__init__', <function Human.__init__ at 0x000001DBC4727160>), ('age', <function Human.age at 0x000001DBC4A58CA0>), ('display', <function Human.display at 0x000001DBC4A58D30>)] Object 1 2 3 4 Has been created [('__init__', <bound method Human.__init__ of <__main__.Human object at 0x000001DBC4708FD0>>), ('age', <bound method Human.age of <__main__.Human object at 0x000001DBC4708FD0>>), ('display', <bound method Human.display of <__main__.Human object at 0x000001DBC4708FD0>>)]
Alterative dir(class).
>>> dir(Human)
[.....
 '__subclasshook__',
 '__weakref__',
 'age',
 'display']
To just show method and not all special methods.
>>> [m for m in dir(Human) if not m.startswith('__')]
['age', 'display']
help(class)