This is a very simple class example for those who are still learning about the subject.
Python, 17 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#---This is the class part---# class Arit: def add(self,a,b): return a+b def subs(self,a,b): return a-b #---This is the part that uses the class---# n1=10 n2=4 operation=Arit() print "The addition is", operation.add(n1,n2) print "The substraction is", operation.subs(n1,n2)
When I was learning about classes I found all examples too complicated. I hope this example helps to clarify things for you. Try adding the multiplication and division methods.
Very good example. I only wonder why the first argument of the methods is "self". Can anyone tell me? Thanks.
Well, i m not sure that such a simple tutorial should be on a recipe site. Refer to Python manual instead, a tutorial is included. Anyway, the reason for the 'self' argument is inherent to object-oriented languages, though most of object-oriented languages, e.g. java, C++, C#, "hide" this argument (the "self" argument in Python methods is the same as the "this" keyword of the languages above). The self keyword is a reference to the object you re executing the method from, and is the only way to manipulate the members of that object. Example:
Thanks for this example and explanation.