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.
The statements defined inside the class must be properly indented.
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)
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.
Total Marks = 207
Average Marks = 69.0
even = 0 #class varaiable
def check(self, num):
print(num," is Even number")
print(num," is Odd number")
x = int(input("Enter a value: "))
When you execute this program, Python accepts the value entered by the user and passes it to the method check through object.
Enter a value: 4
4 is Even number
Enter a value: 5
5 is Odd number