########征服python##########3
1 类的定义与使用
class book: #类的定义
name='kk'
pages=0
print(book.name)
a=book() #类的访问
a.name="book1" #a对象的name的访问
print(a.name)
b=book()
b.name="book2"
print(b.name)
book.name="hello" #通过类名访问name
print(a.name) #打印book1
print(b.name)
print(book.name) #打印hello
2 类的私有成员变量和函数
class book: #类的定义
__price=0 #定义私有成员只能在 内部访问
name='kk'
pages=0
def test_1(self):
print("ok")
def __test2_2(self): #定义为私有的不能访问
print("private")
a=book()
a.test_1()
a.name="book1"
a.__price=20 #对于变量不受影响~~~为什么呀~~~
print(a.__price)
3 通过继承创建类
class book:
name=" "
def __check(self,item): #每个成员函数必须有一个self标量
if item==" ":
return 0
else:
return 1
def show(self):
if self.__check(self.name):
print(self.name)
else:
print("no name")
def __init__(self,name): #这个函数为name赋值
self.name=name
class student(book): #student类继承book类
age=13
def showinfo(self):
self.show() #调用父类的方法
b=student("hah")
b.showinfo()
4 多继承
class book:
name="book1"
def show(self):
print(self.name)
class human:
age=13
def show(self):
print(self.age)
class student(book,human): #student类继承book类 和human类
def showall(self):
print(self.name)
print(self.age)
b=student()
b.showall()
b.show() #以第一个父类为准
class rose(book,human): #student类继承book类 和human类
def showall(self):
print(self.name)
print(self.age)
def show(self):
print("ok")
c=rose()
c.showall()
c.show() #以子类函数为准