关于class 的笔记和想法

868 查看

everything in python is object.
每个object都有一个type,换言之,每个object都是与之对应的type的instance,而且每个type都有各自的method,比如 a= [1,2,3]就是type(int)的一个instance(实例), 1,2,3就是这个对象的内部数据,a.append就是这个object的一个method。创建一个class就是创建一个新的type,如下面这段代码

class Coordinate(object):

def __init__(self, x, y):
    self.x = x
    self.y = y

def __str__(self):
    return “<”+self.x+”,”+self.y+”>” 

def distance(self,other):
    return math.sqrt(sq(self.x - other.x) + sq(self.y-other.y))

创建了一个名为Coordinate的class,这个类被创建出来时就自动调用init函数,若输入下列代码
'a = Coordinate(3, 4)'
那a就是这个class的instance,即a是一个object,这个object有:

  1. type: Coordinate
  2. attibutes
    2.1 an internal date representation(这个例子中是x和y)
    2.2 A set of procedures for interaction with the object(也就是上述所说的方法,即函数init, str和distance)