类
class Person:
def say(a,b):
print("Hello you all! %d"%b)
print(a)
p=Person()
p.say(1)
类中定义的方法,第一个对象总是当前类实例本身
class Person:
def __init__(self,name):
self.name = name
def say(a,b):
print("Hello you all! %d,%s"%(b,a.name))
print(a)
p=Person("MrROY")
p.say(1)
__init__(self,name)相当于JAVA中的构造方法
self.name=name,self中的变量可以直接设置和赋值,不需要提前定义。
类的self可以用来定义对象域,直接在类中指定的变量为类变量。
Python中所有的类成员(包括数据成员)都是 公共的 ,所有的方法都是 有效的 。
只有一个例外:如果你使用的数据成员名称以 双下划线前缀 比如__privatevar
,Python的名称管理体系会有效地把它作为私有变量。
class Person:
popution=110
p1=Person()
print("p1-->%d"%p1.popution)
#让popution加一
Person.popution+=1
p2=Person()
print("p2-->%d"%p2.popution)
结果是:
p1-->110
p2-->111
继承
class Person:
p=0
def __init__(self,name,age):
self.age=age
self.name=name
print("Person initialized %d %s"%(age,name))
class Student(Person):
def __init__(self,name,age,grade):
Person.__init__(self,name,age)
self.grade=grade
s = Student("ROY",100,2007)
print(s.p)
文件操作
poem='''
This is just
a test
for string file'''
f = open("G:/poem.txt","w")
f.write(poem)
f.close()
写文件
f = open("G:/poem.txt","r")
while True:
line=f.readline()
if len(line)==0:
break
print(line)
f.close()
True和False首字母都为大写
异常处理
try:
Print("-----")
except:
print("error")
finally:
print("finally")