Welcome, guest | Sign In | My Account | Store | Cart

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.

3 comments

valerio pachera 13 years, 6 months ago  # | flag

Very good example. I only wonder why the first argument of the methods is "self". Can anyone tell me? Thanks.

Akira Fora 13 years, 6 months ago  # | flag

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:

class SimpleClass:
    def __init__(self):
        self.cumul=0
    def accumulate(self,amount):
        self.cumul = self.cumul + amount

simpleObject = SimpleClass()
print simpleObject.cumul
simpleObject.accumulate(10)
print simpleObject.cumul
Dennis Smith 13 years, 1 month ago  # | flag

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.

Thanks for this example and explanation.

Created by Sergio Castro on Sun, 18 May 2008 (PSF)
Python recipes (4591)
Sergio Castro's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks