class Calculator: #首字母要大写,冒号不能缺 name='Good Calculator' #该行为class的属性 price=18 def add(self,x,y): print(self.name) result = x + y print(result) def minus(self,x,y): result=x-y print(result) def times(self,x,y): print(x*y) def divide(self,x,y): print(x/y) """" >>> cal=Calculator() #注意这里运行class的时候要加"()",否则调用下面函数的时候会出现错误,导致无法调用. >>> cal.name 'Good Calculator' >>> cal.price 18 >>> cal.add(10,20) Good Calculator 30 >>> cal.minus(10,20) -10 >>> cal.times(10,20) 200 >>> cal.divide(10,20) 0.5 >>> """"
1、def 后加self,在类里面的参数,会被传递下来。
2、注意定义自变量cal
等于Calculator
要加括号“()” ,cal=Calculator()
否则运行下面函数的时候会出现错误,导致无法调用。
class类init功能
class Calculator: name='good calculator' price=18 def __init__(self,name,price,height,width,weight): # 注意,这里的下划线是双下划线 self.name=name self.price=price self.h=height self.wi=width self.we=weight """" >>> c=Calculator('bad calculator',18,17,16,15) >>> c.name 'bad calculator' >>> c.price 18 >>> c.h 17 >>> c.wi 16 >>> c.we 15 >>> """"
class Calculator: name='good calculator' price=18 def __init__(self,name,price,hight=10,width=14,weight=16): #后面三个属性设置默认值,查看运行 self.name=name self.price=price self.h=hight self.wi=width self.we=weight """" >>> c=Calculator('bad calculator',18) >>> c.h 10 >>> c.wi 14 >>> c.we 16 >>> c.we=17 >>> c.we 17 """"