面向对象进阶
面向对象进阶
1、类属性
- 
定义 class Demo(object): '''定义类属性''' name = 'lucky' age = 18 d1 = Demo()
- 
调用 可以通过类调用 可以通过对象调用 d1 = Demo() # 通过对象调用 # 类中定义的属性 所有实例化的对象 都拥有 print(d1.name) d2 = Demo() print(d2.name) # 通过类调用 print(Demo.name)
- 
给类绑定属性(增加类属性) 类名.属性名 = 属性值 # 绑定类属性 Demo.sex = 'man' print(d1.sex) print(d2.sex)
- 
类/对象对属性的操作 - hasattr() 判断是否有该属性
- setattr() 设置属性
- getattr() 获取属性值
 print(getattr(Demo, 'name')) setattr(Demo, 'sex', 'man') print(hasattr(Demo, 'name')) print(hasattr(Demo, 'namee'))
2、对象属性
- 
概述 - 通过实例化对象或self对象创建的属性 称为对象属性
- 对象属性只能存在于当前对象中
- 对象属性只能由对象调用
 
- 
创建对象属性 - 类实例化的对象创建
- 通过类的内部的self进行创建
 class Demo: name = 'lucky' # 类中创建对象属性的方法 def create_attr(self, attr, value): # 属性不能传递变量 否则属性名为 当前的变量名 print(attr, value) self.attr = value print(self.__dict__) d1 = Demo() # 创建对象属性sex d1.sex = 'man' # 通过对象属性调用的 print(d1.sex) # 报错 类不能调用对象属性 print(Demo.sex) d1.create_attr('age', 18) print(d1.attr)
- 
类/对象操作属性或方法 - hasattr() 判断是否有该属性
- getattr() 获取该属性值
- setattr() 设置属性值
 print(getattr(d1, 'name')) print(setattr(d1, 'name', 'zhangsan')) print(d1.name) print(hasattr(d1, 'name')) print(hasattr(d1, 'namee'))
- 
注意 - 使用对象创建的属性 只有当前对象拥有 和 别的对象没有关系
- 使用类创建的属性 所有对象都拥有
- 在对象中修改类中的属性 实则为创建了新的和类中同名的对象属性 当调用的时候 优先调用对象属性 如果对象中不存在 则去类中查找该属性 如果类中不存在 则抛出属性错误的异常
- 类中self所创建的属性也为对象属性 哪个对象调用的 则该属性属于哪个对象的
- 对象对类中的所有属性和方法只有使用权 没有操作权
- 类可以修改删除自己类中的属性和方法
 
3、案例
import time
class ATM:
    # 默认ATM中金额为0元
    money = 0
    # 操作的用户
    user = ''
    # 存款
    def set_money(self):
        # 获取用户输入的金额
        # 金额的异常处理   判断存款金额
        money = eval(input('请输入存款金额:'))
        # 更改money金额
        self.money += money
        print('恭喜:{} 存款成功 存款金额为:{} 卡内余额为:{}'.format(self.user, money, self.money))
    # 取款
    def get_money(self):
        # 取款金额和卡内余额的关系
        # 判断当前用户取款金额 是否为 整数的金额 100、200、300
        money = eval(input('请输入要取款的金额'))
        if self.money < money:
            print('抱歉 您卡内余额不足~')
            return
        # 余额的处理
        self.money -= money
        print('恭喜:{} 取款成功!取款金额为:{} 卡内可用余额为:{}'.format(self.user, money, self.money))
    # 查看金额
    def look_money(self):
        print('欢迎:{} 您卡内余额为:{}'.format(self.user, self.money))
user = ATM()
# 欢迎...来办理业务
if __name__ == '__main__':
    print('******************************')
    print('******************************')
    print('*****欢迎来到ATM自助取款机*****')
    print('******************************')
    print('******************************')
    # 输入用户姓名
    user.user = input('请输入当前客户姓名:')
    while True:
        print('**********1    存款********************')
        print('**********2    取款********************')
        print('**********3    查看余额****************')
        choose = eval(input('请输入你要办理的业务'))
        if choose == 1:
            user.set_money()
        elif choose == 2:
            user.get_money()
        elif choose == 3:
            user.look_money()
        else:
            print('抱歉、请重新输入')
        time.sleep(2)
4、对象与类绑定方法
- 
对象绑定方法 - 
直接给对象赋值函数 class Test: name = 'lucky' t1 = Test() def run(self): print(self.name) print('大伟 is running') # run属性存储为 run函数体 t1.run = run t1.run(t1)
- 
使用MethodType进行绑定 from types import MethodType from types import MethodType # 使用MethodType去绑定对象方法 t1.run = MethodType(run, t1) t1.run()注意:对象绑定属性或方法、都只存在于当前的对象中 和其它对象无关 
 
- 
- 
类绑定方法 - 
直接赋值 class Test: pass t1 = Test() def run(self): print(self) print('大伟 is running...') # 直接赋值法 Test.run = run t1.run()
 
- 
- 
使用MethodType进行绑定 from types import MethodType # 使用MethodType进行绑定 Test.run = MethodType(run, Test) print(t1.run())给类绑定属性和方法 所有对象都存在该属性和方法 
5、限制绑定属性
- 
概述 __slots__限制绑定的属性
- 
使用 如果绑定了不允许绑定的属性 则抛出异常 
- 
实例 class Test: # 限定可以绑定age, abc属性 __slots__ = ['age', 'abc'] name = 'lucky' t1 = Test() t1.age = 18 t1.abc = 'abc'
- 
注意 使用 __slots__属性限制 只针对当前对象起作用 对继承的子类不起作用多个属性用列表、元组都可以 
6、对象初始化状态
- 
需求 类创建的多个对象 属性的初始值是不同的 
- 
格式 __init__方法
- 
使用 class Person(object): # 当实例化的时候 动态绑定对象属性 # def __init__(self, name, age, sex): def __init__(self, name='lucky', age=18, sex='man'): self.name = name self.age = age self.sex = sex print('你看我是不是执行了小老弟')调用 zhangsan = Person('张三') print(zhangsan.__dict__)
7、析构方法
- 
作用 释放一些不必要的内存 
- 
格式 __del__在代码执行完自动调用
- 
使用 class Test: def __init__(self, name): self.name = name def say(self): print('我是一个say方法') def __del__(self): print('代码执行完会自动调用') t = Test('lucky') print(t.name) t.say()使用场景 - 释放内存
- 关闭文件句柄
- 关闭数据库的链接
 8、案例
- 
bulletBox.py # 子弹 class BulletBox(object): def __init__(self, count): self.bulletCount = count
- 
gun.py # 枪 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('剩余子弹:{}发'.format(self.bulletBox.bulletCount))
- 
person.py # 人 class Person(object): # 构造方法 实例化的时候 创建对象属性gun def __init__(self, gun): self.gun = gun # 射击 def fire(self): self.gun.shoot() # 填充子弹 def fillBullet(self, count): self.gun.bulletBox.bulletCount = count
- 
main.py from bulletBox import BulletBox # 导入弹夹 from gun import Gun # 导入枪 from person import Person # 导入人 # 实例化弹夹 bulletBox = BulletBox(5) # 枪 gun = Gun(bulletBox) # 实例化人 zhangsan = Person(gun) # 开枪 zhangsan.fire() zhangsan.fillBullet(5) zhangsan.fire()
本文来自博客园,作者:寻月隐君,转载请注明原文链接:https://www.cnblogs.com/QiaoPengjun/p/16021550.html

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号