Class Methods
Python class function or Method is very similar
to ordinary function with a small difference that, the class method must have
the first argument named as self. No
need to pass a value for this argument when we call the method. Python provides
its value automatically. Even if a method takes no arguments, it should be
defined with the first argument called self.
If a method is defined to accept only one argument it will take it as two arguments
ie. self and the defined argument.
When you declare class variable within class,
methods must be prefixed by the class name and dot operator.
Note
The
statements defined inside the class must be properly indented.
class Student:
mark1, mark2, mark3 = 45, 91,
71 #class variable
def process(self): #class method
sum = Student.mark1 +
Student.mark2 + Student.mark3
avg = sum/3
print("Total Marks = ",
sum)
print("Average Marks =
", avg)
return
S=Student()
S.process()
In the above program, after defining the class,
an object S is created. The statement S.process( ), calls the function to get
the required output.
Note that, we have declared three variables
mark1, mark2 and mark3 with the values 45, 91, 71 respectively. We have defined
a method named process with self argument, which means, we are not
going to pass any value to that method. First, the process method adds the
values of the class variables, stores the result in the variable sum, finds the
average and displays the result.
Thus the above code will show the following
output.
Output
Total Marks = 207
Average Marks = 69.0
class Odd_Even:
even = 0 #class varaiable
def check(self, num):
if num%2==0:
print(num," is Even
number")
else:
print(num," is Odd
number")
n=Odd_Even()
x = int(input("Enter a
value: "))
n.check(x)
When you execute this program, Python accepts
the value entered by the user and passes it to the method check through object.
Output 1
Enter a value: 4
4 is Even number
Output 2
Enter a value: 5
5 is Odd number
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.