Class Method in Python


This code defines a class called Student with class attributes name and age and a class method printall(). The printall() method is defined within the class and it prints the values of class attributes name and age.

  • Student.printall() calls the class method and prints the values of class attributes name and age.
  • print(Student.__dict__) prints the class attributes and methods in a dictionary form.
  • getattr(Student, "printall") gets the attribute of the class Student by the name of the attribute which is printall and returns the function definition.
  • getattr(Student, "printall")() gets the attribute of the class Student by the name of the attribute which is printall and calls the function.
  • Student.__dict__['printall']() gets the attribute of the class Student by the name of the attribute which is printall from the class dictionary and calls the function.
  • All three ways of calling the class method printall() will print the same output which is "Name : Tutor Joes", "Age : 25"

Source Code

# Class Methods
class Student:
    name = "Tutor Joes"
    age = 25
 
    def printall():
        print("Name : ", Student.name)
        print("Age  : ", Student.age)
 
 
Student.printall()
print(Student.__dict__)
 
print(getattr(Student, "printall"))
getattr(Student, "printall")()
 
Student.__dict__['printall']()
 
To download raw file Click Here

Output

Name :  Tutor Joes
Age  :  25
{'__module__': '__main__', 'name': 'Tutor Joes', 'age': 25, 'printall': <function Student.printall at 0x000001F08DD5B5E0>, '__dict__': <attribute '__dict__' of 'Student' objects>>, '__weakref__': , '__doc__': None}

Name :  Tutor Joes
Age  :  25
Name :  Tutor Joes
Age  :  25

List of Programs


Sample Programs


Python Database Connection


Python Flask


Python Tkinder Tutorial