**
** 1.class 定义一个类, 后面的类别首字母推荐以大写的形式定义 如
class Calculator: #首字母要大写,冒号不能缺 name='Good Calculator' #该行为class的属性 price=18 def add(self,x,y): print(self.name) result = x + y print(result)(python不加引号) 注意定义自变量cal等于Calculator要加括号,cal=Calculator(),否则运行下面函数的时候会出现错误,导致无法调用. 2.__init__可以初始化class的变量,在运行时给初始值附值。 如:
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)如何设置属性的默认值, 直接在def里输入即可,如下:
def __init__(self,name,price,height=10,width=14,weight=16):3.输入:variable=input() 表示运行后,可以在屏幕中输入一个数字,该数字会赋值给自变量。 4.import: (1)import time。 (2)import time as __,下划线缩写部分可以自己定义,在代码中把time 改名成 t。 (3)from time import time,localtime ,只import自己想要的功能。 (4)from time import * 输入模块的所有功能。 此外还可以定义自己的模块,写好之后默认保存在文件夹****.py内,并同样用import导入。 5.pass语句相当于什么都不执行的空语句。 6.错误处理与回滚:
try: file=open('eeee.txt','r') #会报错的代码 except Exception as e: # 将报错存储在 e 中 print(e)