Object-oriented programming
Python is OOP, usually, each object definition corresponds to some object or concept in the real world a nd the functions that operate on that object correspond to the ways Real-world objects interact.
In Python, every value was actually an object. An object with a state and a collection of methods that it can perform.
The state of an object represents those things, the object knows about itself.
User Defined Classes
1 class Point : 3 """ "" "45 def__init__(self):6 "" "" "" 7self.x = 0 8 SELF.Y = 0
Every class should has a method with the special name _init_. This is Initializer method often called constructor.
A method behaves like a function but it's invoked on a specific instance.
The _str_ method is responsible for returning a string representation as defined by the class creator.
classPoint :"""Point class for representing and manipulating X, y coordinates.""" def __init__(self, INITX, inity):"""Create A new point at the origin"""self.x=INITX self.y=Inity
def _str_ (self):
Return "x=" + str (self.x) + ", y=" + str (SELF.Y)
def GetX (self):
Return self.x
def GetY (self):
Return SELF.Y
def distancefromorigin (self):
Return ((self.x * 2) + (SELF.Y * 2)) * * 0.5
def halfway (self, target):
MX = (self.x + target.x)/2
my = (self.y + target.y)/2
Return point (MX, my)
def distance (Point1, Point2):
Xdiff = Point2.getx ()-Point1.getx ()
Ydiff = Point2.gety ()-point1.gety ()
Dist = MATH.SQRT (Xdiff * * 2 + ydiff * * 2)
Return Dist
P= Point (7,6)#instantiate an object of type pointQ = Point (2,2)#And make a second pointMID = P.halfway (q)
Print (mid)
Print (Mid.getx ())
Print (Mid.gety ())Print(P)
Print (P.getx ())
Print (P.gety ())
Print (P.distancefromorigin ())Print(q) Print (distance (p,q))Print(p isQ
Python-class and Objects