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.





MultiQuote





|