要素:
- class就代表一个类,类似于生物中的一种类型的生物:猫科动物。
- 对“猫科动物”进行属性和行为的添加;属性如:有四条腿,胡须,行为(def)如:run、stop
- 使用的时候需要对类进行定义,如:老虎。
# creat class
class car:
## add behavior
def originmodle(self):
self.window = "white"
# creat objects
motor_car = car()
# add objects attributes
motor_car.window = 'yellow'
print motor_car.window
# two way use fuction
car.originmodle(motor_car)
print motor_car.window
motor_car.originmodle()
print motor_car.window
class cal(object):
def points(self, X, Y):
self.x = X
self.y = Y
def distance(self, other_point):
out = (self.x + other_point.x)/2
return out
P1 = cal()
P2 = cal()
P1.points(3,2)
P2.points(4,5)
print P1.distance(P2)
- 初始化一个类的属性
How to: __init__()
PS:当有了init的初始化函数后,不在需要对P1、P2进行类的声明,直接使用该类,因为函数的首先会运行init的函数内容
class cal(object):
def __init__(self, x, y):
self.points(x, y)
def points(self, X, Y):
self.x = X
self.y = Y
#P1 = cal()
#P2 = cal()
#P1.points(3,2)
#P2.points(4,5)
P1 = cal(3,2)
P2 = cal(4,5)