一.面向对象基础
#类的定义与调用
#定义类使用chass关键字,然后继承至object类、
#2.在类中定义方法,第一个参数必须是self,self代表的是当前这个对象
#3.使用创建一个对象,类名
class Person():
def __init__(self,name,age):
self.name = name
self.age = age
#使用类创建一个对象,类名()
def eat(self):
print('好吃')
p1 = Person('zhiliao',20)
print(p1.name)#调用属性
print(p1.age)
p1.eat()#调用方法
二..访问限制
受保护属性,使用一个下划线开头
class Woman(object):
def __init__(self,age):
self._age = age
w = Woman(12)
print(w._age)
私有属性或者方法,不能被外部调用,但是内部可以调用
class Account():
def __init__(self,a_id,password):
self.a_id = a_id
self.__password = password#私有属性
def __get_list(self):#私有方法
print('不可调用')
return [1,-1.6]
def search_list(self,password):
if password == self.__password:
return self.__get_list()
else:
return None
account = Account(1,123456)
account.search_list(123456)
私有属性也可以有特定的方法属性来调用
print(account._Account__password)
三.练习
#CPU/Ram/Disk
class CPU(object):
'''
CPU类'''
def __init__(self,brand,care,interface):
self.brand = brand
self.care = care
self.interface = interface
class Ram(object):
'''
内存类'''
def __init__(self,brand,size):
self.brand = brand
self.size = size
class Disk(object):
'''
硬盘类'''
def __init__(self,brand,size):
self.brand = brand
self.size = size
class Computer(object):
'''
电脑类'''
def __init__(self,cpu_interface,ram_count,desk_count):
self.cpu_interface = cpu_interface
self.ram_count = ram_count
self.desk_count = desk_count
self.__cpu =None
self.__rams = []
self.__desks = []
def addCpu(self,cpu):
if cpu.interface ==self.cpu_interface:
self.__cpu = cpu
else:
print('型号不符,不能安装')
def addRams(self,ram):
if len(self.__rams) ==self.ram_count:
print('已经满了,不能再装了')
else:
self.__rams.append(ram)
def adddisks(self,disk):
if len(self.__desks) ==self.desk_count:
print('硬盘满了')
else:
self.__desks.append(disk)
def run(self):
if not self.__cpu:
print('没有cpu,电脑不能正常启动')
return
elif len(self.__rams)==0 or len(self.__rams)>self.ram_count:
print('内存不足')
return
elif len(self.__desks)==0 or len(self.__desks)>self.desk_count:
print('硬盘不足')
return
else:
print('所有安装完毕,电脑正常启动')
def main():
#初始化一台电脑
computer = Computer('11211',2,2)
#初始化CPU
cpu = CPU('intel',4,'11211')
#创建两个内存条
ram1 = Ram('jinshidun','4g')
ram2 = Ram('jinshidun', '4g')
#创建两个硬盘
disk1 = Disk('jinshidun','256g')
disk2 = Disk('jinshidun', '256g')
#组装cpu
computer.addCpu(cpu)
#组装内存条
computer.addRams(ram1)
computer.addRams(ram2)
#组装硬盘
computer.adddisks(disk1)
computer.adddisks(disk2)
computer.run()
if __name__ =='__main__':
main()