(1)类的概述
#一种数据类型,本身不占内存空间;用类创建实例化对象,对象占内存空间#
①设计类
类名:首字母大写,其他遵循驼峰原则
属性:
行为(方法/功能):
例: 类名:Wife
属性:sex age height weight faceValue
行为:做饭 洗衣服 拖地
②类格式
class 类名(父类列表):
属性
行为 object:基类,超类,所有类的父类
例:class Person(object):
#定义属性
name=""
age=0
height=0
#方法
def run(self):
print("run")
def eat(self,food):
print("eat"+food)
③实例化对象
对象命=类名(参数列表) 没有参数小括号也不能省略
④访问对象的属性,方法
格式:对象名.属性名
赋值:对象名.属性名=新值
修改属性值:1.直接修改属性的值
2.通过方法修改属性的值
3.通过方法对属性的值进行递增
格式:对象名.方法名(参数列表)
⑤ 对象的初始状态(构造函数)
使用类创建对象的时候自动调用
不显示写出,默认会自动添加一个空的构造函数
def __init__(self,attr...):
self.attr=attr
self....=...
pass
(2)self
self代表类的实例,而非类
对象调用方法,方法中的self代表对象。
self._ class _ 代表类名
(3)析构函数与重写函数
析构函数_ del _() 释放对象时自动调用
在函数里定义的对象,会在***函数结束***时自动释放,这样可以用来减少内存空间的释放
重写函数_ repr _ 与 _ str _
重写:将函数重新写一遍
print(对象名)
_ str _():在调用print打印对象时自动调用,给用户用的 return " "
_ repr _():给机器用的,python解释器里 敲对象后调用的方法
注意:在没有str时,有repr str=repr
(4)访问限制
如果要让内部属性不被外部直接访问,在python中如果在属性前加两个下划线,那么这个属性就变成了私有属性
self.__money = money
不能直接访问类名.__money是因为python解释器把__money变成了_类名__money
#通过内部方法,修改私有属性
def setMoney(self,money):
if money<0:
money =0
self.__money = money
#获取私有属性
def getMoney(self):
return self.__money
__ XX__属于特殊变量,可以直接访问
_X变量 虽然可以访问,但是请视为私有
(5)类实例
人开枪设计子弹
人 类名:person
属性:gun
行为:fire
枪 类名:Gun
属性:bulletBox
行为:shoot
弹夹 类名:BulletBox
属性:bulletCount
行为:
class BulletBox(object): # 弹夹类
def __init__(self, count):
self.bulletCount = count
class Gun(object):
def __init__(self, bulletBox):
self.bulletBox = bulletBox
def shoot(self):
if self.bulletBox.bulletCount == 0:
print("没有子弹了")
else:
self.bulletBox.bulletCount -= 1
print("剩余子弹", self.bulletBox.bulletCount, "发")
class Person(object): # 人类
def __init__(self, gun):
self.gun = gun
def fire(self):
self.gun.shoot()
def fillBullet(self):
self.gun.bulletBox.bulletCount += 1
bulletbox = BulletBox(5)
gun = Gun(bulletbox)
per = Person(gun)
per.fire()
per.fire()
per.fillBullet()
per.fire()
(6)继承:
简化代码,减少冗余
提高代码健壮性
提高代码安全性
多态的前提
单继承实例:
class Person(object):
def __init__(self,name,age,money):
self.name=name
self.age=age
self.__money=money
def setMoney(self,money):
self.__money=money
def getMoney():
return self.__money
class Student(Person):
def __init__(self,name,age):
#调用父类中的__init__
super(Student,self).__init__(name,age)
stu = Student("tom",18,12345)
print(stu.name,stu.age)
print(stu.getMoney()) #通过继承过来的公用方法访问私有属性
多继承实例:
class Father(object): #父亲类
def __init__(self,money):
self.money=money
def play(self):
print("play")
def func(self):
print("func")
class Mother(object): #母亲类
def __init__(self,faceValue):
self.faceValue=faceValue
def eat(self):
print("eat")
def func(self):
print("func")
class Child(Father,Mother): #孩子类
def __init__(self,money,faceValue):
#写法
Father.__init__(self,money)
Mother.__init__(self,faceValue)
#父类中方法名相同,默认调用在括号中排前面的父类中的方法