📖 generic · 12th TN - English Medium · COMPUTER SCIENCE · Page 176question

PYTHON CLASSES AND OBJECTS · Part 2

Chapter 3: 4 · COMPUTER SCIENCE

the members of the class. The first two print statements simply print the value of class variable x and y and the last print statement add the two values and print the result. 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 parameter named as self .

No need to pass a value for this parameter when we call the method. Python provides its value automatically. Even if a method takes no arguments, it should be defined with the first parameter called self . If a method is defined to accept only one parameter it will take it as two arguments ie.

self and the defined parameter. When you access 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. • Parameters are the variables in the function definition.

• Arguments are the values passed to the function definition. Note class Student: mark1, mark2, mark3 = , , #class variable def process(self): #class method sum = Student.mark1 + Student.mark2 + Student.mark3 avg = sum/ print("Total Marks = ", sum) print("Average Marks = ", avg) return S=Student() S.process() Example: Program to find total and average marks using class 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. 12th Computer Chapter - - Python Classes and Objects Note that, we have declared three variables mark1, mark2 and mark3 with the values , , 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 = Average Marks = .

class : def check(self, num): if num% == :

Related topics

Have a question about this topic?

Get an AI answer grounded in your actual textbook — with the exact page reference.

Ask AI about this topic →