Python Classes

"everything in python is an object"

"object oriented programming"

import cars

mycar = cars.Toyota("prius")
mycar.start()
mycar.setSpeed(20.0)
mycar.setDirection(20, units="degrees")
mycar.drive(2.0)
mycar.fly()

In [ ]:
class Complex(object):
    """ this is my simple class describing a complex number"""
    def __init__(self, Re=0.0, Im=0.0):
        self.Re = Re
        self.Im = Im
        
    def print(self):
        print("(%g,%g)" % (self.Re,self.Im))
        
    def Real(self):
        return self.Re
    
    def Imag(self):
        return self.Im
    
    def __add__(self,z):
        x = self.Re + z.Real()
        y = self.Im + z.Imag()
        return Complex(x,y)
    
    def __str__(self):
        return "xxx"         # not yet implemented   
    
    def plot(self):
        print("I cannot plot %s"  % str(self))

In [ ]:
a = Complex(0,1)
b = Complex(1,0)

In [ ]:
a.print()
b.print()

In [ ]:
c=a+b
c.print()

In [ ]:
c.plot()

In [ ]:
print(c)

In [ ]:
type(c)