Page 1 of 1

An Introduction to Classes in Python

#1 bodom658  Icon User is offline

  • Villiage Idiom
  • member icon

Reputation: 113
  • View blog
  • Posts: 1,123
  • Joined: 22-February 08

Posted 03 April 2009 - 09:40 AM

Python is a very versatile, powerful programming language that a lot of people seem to either not respect or just take for granted. But, the point of this entry is not to rant about such silly things, it is to teach you how to write a simple class in Python.

Please note: I recomend using a text editor to write the code, then save it as a .py file, and then run it from the command line, using C:\Python26\python.exe <file name> from the file directory you saved this .py file in. For windows, shift right click in the directory and hit open command window here. For linux and mac users, use a terminal window with the file path changed as necessary, or removed. Python should be in the path for at least Linux systems.

Alternatively, use "external tools" if they are available in your text editor, and set it up to run the script with the same command and arguments as stated above. For Windows, I recommend Crimson Editor. For Linux, Geany or Eric work well


With all that being said, let's get started.

Classes in python are created using the 'class' keyword, followed by a name for the class, and a colon. The class I will be writing is a small class that handles a complex number, and will contain a few methods.

import math #we will use this later

class Complex:



simple right?

After you get this down, we can start thinking of data members. Data members are your variables contained in your class. These must be initialized when you enter them into your script. However, you can change their type as you go, so just initialize these both to zero, in any situation in which you will be setting the values manually later.

import math

class Complex:
	real = 0
	imaginary = 0



Ok, we are doing good so far. You may be wondering how it is we are going to set these. Well, if you have any experience in C++, Java, C# or other OOP, you know that you normally have a constructor that will go ahead and set these variables. In Python, we use the __init__ function. We have 2 data members, and both of them should be set at the time the object is created, as each object represents a complex number. Therefore, we will have 3 parameters for this function, which I shall call 'self', 'a', and 'b'. self is comparable to the C# term 'this', in that it is the object itself. This will allow us to manipulate variables and call methods from within the function. This parameter, 'self', should be included in every function in your class, as this will be your key to all the function members. Also, failure to do so will result in an error. We wouldn't want that, would we?

So lets get this __init__ class written out.
We basically want to set real and imaginary to some numbers given to the function through the variables a and b, the function arguments I mentioned before.

It will look like this:
import math

class Complex:
	real = 0
	imaginary = 0
	def __init__(self, a, b):
		self.real = a
		self.imaginary = b



If you have any previous experience to python, this should all look pretty straight forward, except for this 'self' variable. 'self' tells the function that the variable its referring to, the one after the '.' is in the class, not the function. This allows for re use of the data member names in the functions themselves. It's a little tricky to remember at first, but after being told your variable does not exist a million times, you will get it.

I am going to add 2 more functions to this as well, both of which you should be able to interpret.
NOTE: the return keyword returns the value specified on the right hand side.

This makes our full class look like:
import math

class Complex:
	real = 0
	imaginary = 0
	def __init__(self, a, b):
		self.real = a
		self.imaginary = b
	def __Mag(self):
		return math.sqrt(pow(self.real, 2) + pow(self.imaginary, 2))
	def Ang(self):
		return math.acos(self.real/self.Mag())



OK, so how do we use this in a function now?

We create objects like we create variables. basically:
MyObject = Classname(#parameters)



The script knows to go ahead and call the __init__ function, and passes the parameters.

The following is a function which shows how to call methods from a class:
def __main():
	a = input('Enter R1 >>> ')
	b = input('Enter X1 >>> ')
	c = input('Enter R2 >>> ')
	d = input('Enter X2 >>> ')
	E = Complex(a, b)
	F = Complex(c, d)
	print "Distance Between the Points is:", __distance(E, F)
	print "Point 1 in polar --> ", E.Mag(), " @ " , E.Ang()*180/math.pi, "degrees"
	print "Point 2 in polar --> ", F.Mag(), " @ " , F.Ang()*180/math.pi, "degrees"



Note that we do not need to pass the 'self' parameter. We ignore it unless we are writing within the class.
Also, there is the __distance(E,F) function, which is an external function I wrote, but is included in the code shown below

Here is the script as a complete entity:
#Finds the distance between two points
import math

class Complex:
	real = 0
	imaginary = 0
	def __init__(self, a, b):
		self.real = a
		self.imaginary = b
	def __Mag(self):
		return math.sqrt(pow(self.real, 2) + pow(self.imaginary, 2))
	def Ang(self):
		return math.acos(self.real/self.Mag())

#retuns the distance between (x1, y1) and (x2, y2)
def __distance(a, b):
	return math.sqrt(pow(b.real-a.real, 2)+pow(b.imaginary-a.imaginary, 2))

#gets numbers and calls distance
def __main():
	a = input('Enter R1 >>> ')
	b = input('Enter X1 >>> ')
	c = input('Enter R2 >>> ')
	d = input('Enter X2 >>> ')
	E = Complex(a, b)
	F = Complex(c, d)
	print "Distance Between the Points is:", __distance(E, F)
	print "Point 1 in polar --> ", E.Mag(), " @ " , E.Ang()*180/math.pi, "degrees"
	print "Point 2 in polar --> ", F.Mag(), " @ " , F.Ang()*180/math.pi, "degrees"

#run the script
__main()



Not too bad!

One last thing I should mention, which many of you may have been wondering about is encapsulation. Python does not really support encapsulation of data, and does not provide the 'private', 'protected' or 'public' keywords you may be used to. That being said, you can declare a function as __functionname__ (note the double _ on each side). This will make the programmer have to use the following to call the function: obj._classname__functionname__. This can prevent errors, and is really the only alternative.

Any questions, concerns, or errors, please! Comment! I love feedback.

Is This A Good Question/Topic? 1
  • +

Replies To: An Introduction to Classes in Python

#2 bodom658  Icon User is offline

  • Villiage Idiom
  • member icon

Reputation: 113
  • View blog
  • Posts: 1,123
  • Joined: 22-February 08

Posted 10 April 2009 - 05:46 PM

please note: "you can declare a function as __functionname__ (note the double _ on each side)" should read "you can declare a function as __functionname (note the double _ on the front side)"

Also, any variables should be declared and initialized in the __init__ function.

That is all, sorry if I caused anyone problems.
Was This Post Helpful? 0
  • +
  • -

#3 CMIT  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 25-February 12

Posted 26 February 2012 - 02:22 AM

For some reason __Mag was not working... So when I took out the __ in front of the declaration everything worked fine assuming the math is right... Is there any particular reason for __ infront of it on 'def __mag(self):' ?

Enter R1 >>> 1
Enter X1 >>> 2
Enter R2 >>> 3
Enter X2 >>> 4
Distance between the Points is: 2.82842712475
Point 1 in polar --> 2.2360679775 @ 63.4349488229 degrees
Point 2 in polar --> 5.0 @ 53.1301023542 degrees
Was This Post Helpful? 0
  • +
  • -

#4 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Posted 10 May 2012 - 04:18 PM

Why don't you just edit the error out of your tutorial? If you can't, ask a mod to do it.
Was This Post Helpful? 0
  • +
  • -

#5 scalt  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 63
  • View blog
  • Posts: 342
  • Joined: 22-November 07

Posted 19 November 2012 - 04:14 PM

In your tutorial you mention initialising data members when creating your class - 'real' and 'imaginary' - by setting them to 0, ie:

import math

class Complex:
	real = 0
	imaginary = 0
	def __init__(self, a, B)/>/>:
		self.real = a
		self.imaginary = b




You should note that 'real' and 'imaginary' are very different to 'self.real' and 'self.imaginary'. By creating 'non self' variables you are actually creating the equivalent of a static variable that persists between instances. It will not directly affect your code here because aside from setting them to '0' you don't do anything else and the 'self.real' and 'self.imaginary' variables are totally separate because they belong to a specific instance of 'Complex', however they are redundant and could be removed.

Also I think '__Mag' should be changed to 'Mag' in the final code section, I get an error when I try to run 'E.Mag()' (goes away if I just eliminate the '__').

This post has been edited by scalt: 21 November 2012 - 02:05 PM

Was This Post Helpful? 0
  • +
  • -

#6 MrAdo  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 05-January 13

Posted 05 January 2013 - 01:57 AM

Thanks you for this great tutorial.
I really want to learn code in Python because many people said me that is very powerfull language and that I should start learning but I have one problem.
When I want to start program it shows me the same error constatly
C:\Python27\python.exe: can't open file 'test.py': [Errno 2] No such file or directory

When I'm starting program I'm using Windows PowerShell

Here is image and as you can see there is that missing file and I really dont understand why it show this error

http://i.imm.io/RKBB.png

Thank you
Was This Post Helpful? 0
  • +
  • -

#7 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3369
  • View blog
  • Posts: 11,413
  • Joined: 12-December 12

Posted 05 January 2013 - 04:05 AM

C:\Python27\python.exe C:\Python27\test.py

or move to that directory.

Although, this is not the correct place to post this question.

This post has been edited by andrewsw: 05 January 2013 - 04:07 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1