一.类的实例化
例如info1=showInfo(),注意类的方法参数改为self
二.实例属性,类属性
a.改变类属性,实例属性跟着改变
b.修改实例属性,只会影响实例自身
三.实例方法,类方法
a.类方法可重写
类.原始函数=新函数
b.实例方法不能修改
例子:
class showInfo():
var1='aaa'
def showLine(self):
print("--------我是类的函数-------------我的参数是:%s"%self.var1)
#类的实例化
info1=showInfo()
info2=showInfo()
print(info1.var1)
info1.showLine()
def showNewLine(self):
print("--------我是新的函数-------------我的参数是:%s"%self.var1)
showInfo.var1='bbb'
showInfo.var2='ccc'
#改变类属性,实例属性跟着改变
print(info1.var1)
print(info2.var1)
print(info1.var2)
#修改实例属性,只会影响实例自身
info1.var1='ddd'
print(info1.var1)
print(info2.var1)
#类方法可重写
showInfo.showLine=showNewLine
info1.showLine()
打印结果:
aaa
--------我是类的函数-------------我的参数是:aaa
bbb
bbb
ccc
ddd
bbb
--------我是新的函数-------------我的参数是:ddd
四.初始化函数def init(self)
例子:
class form():
def __init__(self,num):
self.num=num
def printForm(self):
for i in range(1,self.num+1):
for x in range(1,i+1):
print( '%d X %d = %d' % (i ,x ,i*x) ,end = ' ' )
print('')
form1=form(3)
form1.printForm()
form2=form(5)
form2.printForm()
打印结果:
1 X 1 = 1
2 X 1 = 2 2 X 2 = 4
3 X 1 = 3 3 X 2 = 6 3 X 3 = 9
1 X 1 = 1
2 X 1 = 2 2 X 2 = 4
3 X 1 = 3 3 X 2 = 6 3 X 3 = 9
4 X 1 = 4 4 X 2 = 8 4 X 3 = 12 4 X 4 = 16
5 X 1 = 5 5 X 2 = 10 5 X 3 = 15 5 X 4 = 20 5 X 5 = 25
5
五.继承
a.class 子类(父类)
b.子类继承父类的方法
c.子类可以改写父类的就去
d.子类可以新加属性和方法
e.可多继承
例子:
class formUpGrade(form):
def __init__(self,newNum):
self.newNum=newNum
def printformUpGrade(self):
print("我是子类的新方法")
def printForm(self):
print("我是父类的方法,但我已经改写了")
formUpGrade1=formUpGrade(3)
formUpGrade1.printForm()
formUpGrade1.printformUpGrade()
print(formUpGrade1.newNum)
打印结果:
我是父类的方法,但我已经改写了
我是子类的新方法
3