#

# 一、type、object和class之间的关系

class是由type创建的,object是所有类需要继承的顶层基类。

# type->int->1
# type->class->obj
a=1
b="abc"
print(type(1))
print(type(int))
print(type(b))
print(type(str))

class Student:
    pass

stu = Student()
print(type(stu))
print(type(Student))
print(int.__bases__)
print(str.__bases__)
print(Student.__bases__)
print(type.__bases__)
print(object.__bases__)
print(type(object))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 二、多态

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


class Dog(object):
    def say(self):
        print("i am a fish")

class Duck(object):
    def say(self):
        print("i am a duck")
        
animal_list = [Cat, Dog, Duck]
for animal in animal_list:
    animal().say()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 三、抽象基类

可以理解为java里面的接口

#我们去检查某个类是否有某种方法
class Company(object):
    def __init__(self, employee_list):
        self.employee = employee_list

    def __len__(self):
        return len(self.employee)


com = Company(["bobby1","bobby2"])
print(hasattr(com, "__len__"))

#我们在某些情况之下希望判定某个对象的类型
from collections.abc import Sized
isinstance(com, Sized)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#我们需要强制某个子类必须实现某些方法
#实现了一个web框架,集成cache(redis, cache, memorychache)
#需要设计一个抽象基类, 指定子类必须实现某些方法

#如何去模拟一个抽象基类

import abc
from collections.abc import *


class CacheBase(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def get(self, key):
        pass

    @abc.abstractmethod
    def set(self, key, value):
        pass
# class CacheBase():
#     def get(self, key):
#         raise NotImplementedError
#     def set(self, key, value):
#         raise NotImplementedError
#
class RedisCache(CacheBase):
    def set(self, key, value):
        pass

# redis_cache = RedisCache()
# redis_cache.set("key", "value")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
更新时间: 2/23/2023, 3:19:23 PM