Python-class and Objects

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.