Instance Method in Python


This code defines a class called Student which has a class attribute name and age and a class method printall(). The printall() method takes one parameter self and gender.

When creating an object of the class, o=Student(), you can call the printall() method using the object and providing the additional parameter gender as an argument. For example, o.printall("Male") or by using the class name and passing the object and the argument as Student.printall(o,"Male").

When you try to call o.printall() or Student.printall(o) without providing the required parameter gender you get TypeError as "Missing 1 required positional argument: 'gender'"

This is because, in method definition, we have defined two parameters self and gender and if we call the method without providing both the parameters, it will raise an error.


Source Code

# instance Methods
class Student:
    name = "Tutor Joes"
    age = 25
 
    def printall(self,gender):
        print("Name : ", Student.name)
        print("Age  : ", Student.age)
        print("Gender  : ", gender)
 
o=Student()
"""
o.printall()
Student.printall(o)
"""
o.printall("Male")
Student.printall(o,"Male")
To download raw file Click Here

Output

Name :  Tutor Joes
Age  :  25
Gender  :  Male
Name :  Tutor Joes
Age  :  25
Gender  :  Male

List of Programs


Sample Programs


Python Database Connection


Python Flask


Python Tkinder Tutorial