class Calc:
def calcadd(self,x,y):
return x+y
def calcreduce(self,x,y):
return x-y
def calcmultiply(self,x,y):
return x*y
def calcdeviate(self,x,y):
return x/y
new_calc= Calc()
print("相加的结果是%s"%new_calc.calcadd(20, 50))
print("相乘的结果是%s"%new_calc.calcmultiply(23, 50))
print("相除的结果是%s"%new_calc.calcdeviate(30, 50))
print("相减的结果是%s"%new_calc.calcreduce(20, 50))
def coord_chng(x,y): #定义一个全局函数,模拟坐标值变换
return (abs(x),abs(y)) #将x,y 值求绝对值后返回
class Cat: #定义一个类Cat
def __init__ (self,x=0,y=0): #定义一个构造方法,
self.x=x
self.y=y
self.disp_point() #构造函数中调用类中的方法disp_point()
def move(self,x,y): #定义一个方法move()
x,y = coord_chng(x,y) #调用全局函数,坐标变换
self.edit_point(x,y) #调用类中的方法edit_point()
self.disp_point() #调用类中的方法disp_point()
def edit_point(self,x,y): #定义一个方法
self.x += x
self.y += y
def disp_point(self): #定义一个方法
print("当前位置:(%d,%d)"% (self.x,self.y))
cat_a= Cat() #实例化Cat()类
cat_a.move(2,4) #调用cat_a实例的方法move()
cat_a.move(-9,6) #调用cat_a实例的方法move()
cat_a.move(12,-16)#调用cat_a实例的方法move()
如下图所示,coord_chng()是全局函数,主要作用是将输入的x,y转换成绝对值后输出;edit_point()和disp_point()是类自身的两个方法,被另一个方法move()调用。
cat_a=Cat() 即创建一个cat_a的对象,属于Cat类,即初始化x=0,y=0;在def __init__()中调用disp_point()方法,显示位置为0,0
cat_a,move(2,4) 即调用上图程序,先将2,4绝对值,再通过edit_point()方法,在原基础上加上x,y值,得到最新的x,y,再调用disp_point()方法打印出来位置。