python深入类和对象

声明:学习笔记,参考B站视频 https://www.bilibili.com/video/BV1Cq4y1Q7Qv?p=12

鸭子类型和多态

# -*- coding: utf-8 -*-

'''
鸭子类型
    当看到一只鸟走起来像鸭子
    游泳起来像鸭子,叫起来也像鸭子
    那么这只鸟就可以被成为鸭子
'''

class Cat(object):
    def say(self):
        print('i am a cat')


class Dog(object):
    def say(self):
        print('i am a dog')


class Duck(object):
    def say(self):
        print('i am a duck')


animal_list = [Cat, Dog, Duck]
for animal in animal_list:
    # 都有共同的say方法
    animal().say()
'''
运行结果:
    i am a cat
    i am a dog
    i am a duck
'''

'''
多态:
    python中不一定需要非要继承某个类才可以实现某个方法
    所有类都实现了一个共同的方法(方法名一样)就可以实现多态
'''
a = [1, 2]
b = [3, 4]

tuple_list = [5, 6]
set_list = set()
set_list.add(7)
set_list.add(8)

# extend(可迭代)  
a.extend(b)
print(a)  # [1, 2, 3, 4]
b.extend(tuple_list)
print(b)  # [3, 4, 5, 6]
tuple_list.extend(set_list)
print(tuple_list)  # [5, 6, 8, 7]

isinstance和type的区别

# -*- coding: utf-8 -*-

class A:
    pass

class B(A):
    pass

b = B()

# isinstance()判断对象类型  推荐使用
print(isinstance(b,B))  # True
print(isinstance(b,A))  # True

print(type(b))  # <class '__main__.B'>

# type判断对象类型 但是对继承关系判断有误差
# (is 判断id 是否相同) / (=  判断值 是否相同)
print(type(b) is B)     # True
print(type(b) is A)     # False

类变量和实例变量

# -*- coding: utf-8 -*-

class A:
    # 类变量
    aa = 11

    def __init__(self, x, y):
        # 实例变量(带self的)
        self.x = x
        self.y = y


a = A(1, 2)
# 1.1实例首先查找自身是否有这个属性
print(a.x)  # 1
print(a.y)  # 1
# 1.2如果实例自身没有这个变量时,会向上到类变量中查找
print(a.aa)  # 11

# 2.类调用类属性不会向下查找
print(A.aa)  # 11
# 如果类调用实例属性则会报错
# print(A.x)  # AttributeError: type object 'A' has no attribute 'x'

# 3.类属性修改后 实例调用的类属性也会被修改
A.aa = 22
print(a.aa)  # 22

# 4.实例中类属性的值被修改后 不会影响类的属性值
a.aa = 100	# 新建实例a的变量aa 并赋值100
print(a.aa)  # 100
print(A.aa)  # 22

# 5.类变量所有实例共享
b = A(3, 5)
print(b.aa)  # 22

实例方法

# -*- coding: utf-8 -*-

class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    def __str__(self):
        return '{}/{}/{}'.format(self.year, self.month, self.day)

    # 实例方法(最常用的定义方式)
    def tomorrow(self):
        self.day += 1


if __name__ == '__main__':
    new_day = Date(2018, 12, 31)
    print(new_day)  # 2018/12/31
    new_day.tomorrow()  # --> tomorrow(new_day)
    print(new_day)  # 2018/12/32

静态方法 @staticmethod

# -*- coding: utf-8 -*-

class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    def __str__(self):
        return '{}/{}/{}'.format(self.year, self.month, self.day)

    # 静态方法 @staticmethod
    @staticmethod
    def parse_from_string(date_str):
        year, month, day = tuple(date_str.split('-'))
        # 静态方法中 需要注意类名(Date需与类名Date一致)
        return Date(int(year), int(month), int(day))

    @staticmethod
    def from_string(date_str):
        year, month, day = tuple(date_str.split('-'))
        if year > 2000:
            # 这种情况推荐使用 静态方法
            return True
        else:
            return False


if __name__ == '__main__':
    '''
    不使用静态方法示例(繁琐 每个对象的调用都有重复操作)
    '''
    date_str = '2018-12-31'
    # tuple 用来拆包
    year, month, day = tuple(date_str.split('-'))
    new_day = Date(int(year), int(month), int(day))
    print(new_day)  # 2018/12/31

    '''
    使用静态方法(staticmethod)后的示例(直接定义到类内部中)
    '''
    new_day = Date.parse_from_string('2018-12-31')
    print(new_day)  # 2018/12/31

类方法 @classmethod

# -*- coding: utf-8 -*-

class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    def __str__(self):
        return '{}/{}/{}'.format(self.year, self.month, self.day)

    # 类方法
    @classmethod
    def parse_from_string(cls, date_str):
        year, month, day = tuple(date_str.split('-'))
        # cls 可以解决掉静态方法中 需要注意类名的弊端
        return cls(int(year), int(month), int(day))


if __name__ == '__main__':
    '''
    类方法比静态方法灵活
    '''
    new_day = Date.parse_from_string('2018-12-31')
    print(new_day)  # 2018/12/31

数据封装和私有属性

# -*- coding: utf-8 -*-

class Person:
    def __init__(self):
        # 双下划线开头的属性(变量) 即私有属性
        self.__total_money = 0

    def save_money(self, money):
        self.__total_money += money

    def get_total_money(self):
        return self.__total_money


if __name__ == '__main__':
    bll = Person()
    # print(zhangsan.__total_money)   
    # AttributeError: 'User' object has no attribute '__total_money'
    
    # 私有属性的访问方式
    print(bll._Person__total_money)
    bll.save_money(1000)
    total_money = bll.get_total_money()
    print(total_money)

对象的自省机制

# -*- coding: utf-8 -*-
class Person():
    name = 'bll'

class Student(Person):
    def __init__(self, scool_name):
        self.scool_name = scool_name


if __name__ == '__main__':

    # 自省机制 就是 通过一定的机制 查询对象的内部结构
    student = Student('ABCD')

    # 通过__dict__查看实例属性
    print(student.__dict__) # {'scool_name': 'ABCD'}

    # 通过__dict__查看类属性
    print(Person.__dict__)
    # {'__module__': '__main__', 'name': 'bll', 
    #'__dict__': <attribute '__dict__' of 'Person' objects>, 
    #'__weakref__': <attribute '__weakref__' of 'Person' objects>,
    # '__doc__': None}

    # 修改__dict__的属性值
    student.__dict__["scool_name"] = 'DCBA'
    print(student.__dict__)     # {'scool_name': 'DCBA'}

    # dir() 显示对象更详细的属性(没有属性值)
    print(dir(student))
    # ['__class__', '__delattr__', '__dict__', '__dir__',
    # '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
    # '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__',
    # '__lt__', '__module__', '__ne__', '__new__', '__reduce__', 
    #'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', 
    #'__str__', '__subclasshook__', '__weakref__', 'name', 'scool_name']

super()与mro的关系

# -*- coding: utf-8 -*-

class A:
    def __init__(self):
        print('A')


class B(A):
    def __init__(self):
        print('B')
        super().__init__()


class C(A):
    def __init__(self):
        print('C')
        super().__init__()


class D(B, C):
    def __init__(self):
        print('D')
        super(D, self).__init__()


if __name__ == '__main__':
    # super()是按照mro的顺序来确认继承顺序
    print(D.__mro__)
    # (<class '__main__.D'>, <class '__main__.B'>,
    # <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)

    d = D()
    '''
    D
    B
    C
    A
    '''

with() 上下文管理

# -*- coding: utf-8 -*-

# try...except...finally 方式操作文件
def open_file():
    try:
        print('open file')
        raise FileNotFoundError
        return 1
    except FileNotFoundError as e:
        print('file not found')
        return 2
    else:
        # 没有抛异常时才执行
        print('file option')
        return 3
    finally:
        # 都会运行 资源释放
        print('finally close file')
        return 4

# 上下文管理器协议
class Sample():
    # 默认加载资源
    def __enter__(self):
        print('enter')
        return self
    
    # 自动释放资源
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('exit')

    def do_something(self):
        print('do something')


if __name__ == '__main__':

    file = open_file()
    '''
    1. 首先将teturn 的 2 压入到栈中
    2. 再将tetern 的 4 再压入到栈中
    3. 在栈顶中取出一个 4 返回
    4. 如果去掉finally 则会正常返回2
    '''
    print(file)     # 4

	# with()上下文管理
    with Sample() as s:
        s.do_something() 
    '''
    enter
    do something
    exit
    '''

contextlib简化上下文管理器

# -*- coding: utf-8 -*-

import contextlib

@contextlib.contextmanager
def file_open(file_name):
    print('file open')
    # 生成器
    yield
    print('file close')


with file_open('test.txt') as f:
    print('file processing')
'''
运行结果:
    file open
    file processing
    file close
'''
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值