码迷,mamicode.com
首页 > 编程语言 > 详细

Python - Class and Objects

时间:2016-06-30 23:13:29      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

Object-oriented programming

Python is OOP, Usually, each object definition corresponds to some object or concept in the real world and the functions that operate on that object correspond to the ways real-world objects interact. 

In python, every value is actually an object. An object has a state and a collection of methods that it can perform.

The state of an object represents those things that the object knows about itself. 

技术分享

 

User Defined Classes

技术分享

 

1  class Point:
3     """ Point class for representing and manipulating x,y coordinates. """
4 
5     def __init__(self):
6         """ Create a new point at the origin """
7         self.x = 0
8         self.y = 0

 

Every class should have a method with the special name _init_. This is Initializer method often called constructor.

A method behaves like a function but it is invoked on a specific instance.

The _str_ method is responsible for returning a string representation as defined by the class creator. 

 

class Point:
    """ 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 Point q = Point(2,2) # and make a second point mid = 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 is q)

技术分享

 

技术分享

 

 

Python - Class and Objects

标签:

原文地址:http://www.cnblogs.com/elewei/p/5631478.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!