Python之面向对象知识整理

""""""
# 1. 谈谈你理解的面向对象?
"""
    - 封装:
        - 将一些函数封装到一个类中。
            class DB(object):
                def ...
                def ...
                def ...
                def ...
            class Cache:
                ...
                ...
        - 将一些数据封装到一个对象中。
            
            class Response(object):
                def __init__(self):
                    self.status = False
                    self.error = None
                    self.data = None
                @property
                def json(self):
                    return self.__dict__
            def index(request):
                result = Response()
                try:
                    result.status = True
                    result.data = '数据'
                except Exception as e:
                    result.error = '处理失败'
                return JsonResponse(result.json)
    - 继承:
        - super
        - self到底是谁?
        
    - 多态(鸭子模型)

"""

# 2. super的作用?
"""
class Base(object):
    def func(self):
        print('base.func')
        super().func()


class Foo(object):
    def func(self):
        print('foo.func')


class Bar(Base,Foo):
    pass
"""
"""
obj = Bar()
obj.func() # Bar -> Base -> Foo
"""
"""
obj = Base()
obj.func() # base
"""

# 3. self到底是谁?

# 4. 鸭子模型
# python
"""
def func(arg):
    arg.send() # arg可以是任意对象,必须有send方法
"""
# java
"""
def func(string arg):
    arg.send() # arg可以是string的对象也可以string的派生类的对象。
"""

# 5. 面向对象的应用场景?
"""
    drf来进行描述。
        - 视图,你在写接口时都继承过哪些类?
        - request封装
"""

# 6. @classmethod和@staticmethod的区别?


# 7. 私有和公有(成员修饰符)

# 8. 成员
"""
    class Foo:
        a1 = 123  # 类变量/静态字段/静态数据
        def __init__(self):
            self.name = 'dogjian' # 实例变量/字段/属性
        
        def func(self):
            pass
        
        @classmethod
        def func(cls):
            pass
        
        @staticmethod
        def func():
            pass 
        
        @property
        def json(self):
            return ...
"""

# 9. 对象和对象的相加
"""
class Foo(object):
    def __init__(self,num):
        self.num = num
    def __add__(self, other):
        return self.num + other.a1

class Bar(object):
    def __init__(self,a1):
        self.a1 = a1

obj1 = Foo(9)
obj2 = Bar(11)

result = obj1 + obj2
print(result)
"""

# 10.特殊方法
"""
    __dict__
    __call__
    __new__
        - 序列化
        - 单例模式
        
        from rest_framework.serializers import Serializer
        class Test(Serializer):
            pass
        ser = Test(instance='',many=True)
    __getitem__
    __setitem__
    __delitem__
        class Session(object):
        
            def __setitem__(self, key, value):
                print(key,value)
        
            def __getitem__(self, item):
                return 1
        
            def __delitem__(self, key):
                pass
            
        obj = Session()
        obj['x1'] = 123
        obj['x1']
        del obj['x1']
    __iter__
    __enter__  
    __exit__
    ...

"""

# 11. 手写单例模式
"""
import time
import threading
class Singleton(object):
    lock = threading.RLock()
    instance = None

    def __new__(cls, *args, **kwargs):
        if cls.instance:
            return cls.instance
        with cls.lock:
            if not cls.instance:
                cls.instance = super().__new__(cls)
            return cls.instance

def task(arg):
    obj = Singleton()
    print(obj)
for i in range(10):
    t = threading.Thread(target=task,args=(i,))
    t.start()
time.sleep(100)

obj = Singleton()
"""

# 12. setitem
"""
class Session(object):

    def __setitem__(self, key, value):
        print(key,value)

    def __getitem__(self, item):
        return 1

    def __delitem__(self, key):
        pass

obj = Session()
obj['x1'] = 123
obj['x1']
del obj['x1']
"""

# 13. 面向对象上下文管理 *****
"""
class Foo(object):

    def __enter__(self):
        print('进入')
        return 666

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('退出')


obj = Foo()

with obj as x1:
    print(x1)  # 此时的x1是__enter__返回return的值
    print('操作中...')
"""

# 14. 自己通过面向对象实现一个“栈”

# class Stack(object):
#
#     def __init__(self):
#         self.container = []
#
#     def push(self, value):
#         """
#         向栈插入数据
#         :param value:
#         :return:
#         """
#         self.container.append(value)
#
#     def pop(self):
#         """
#         从栈中取走数据
#         :return:
#         """
#         return self.container.pop()


# 15. metaclass

#
# class Foo(object):
#     country = '中国'
#
#     def func(self):
#         return 123

# 参数1:类名
# 参数2:继承
# 参数3:成员
# Foo = type('Foo',(object,),{'country':'中国','func':lambda self:123})

# 对象
# obj = Foo()
# ret = obj.func()
# print(ret)

############ 结论:对象是由类创建;类是由type创建;
# class MyType(type):
#     def __init__(self,*args,**kwargs):
#         super().__init__(*args,**kwargs)
#
# class Foo(object,metaclass=MyType):
#     country = '中国'
#     def func(self):
#         return 123
############ metaclass作用:对象是由类创建;类默认是由type创建;metaclass可以指定让类由具体哪一个type创建。
"""
class MyType(type):
    def __init__(self,*args,**kwargs):
        print(args)
        super().__init__(*args,**kwargs)
class Foo(metaclass=MyType):
    pass
class Bar(Foo):
    pass
"""
############ 结论:如果一个类的基类中指定了metaclass,那么派生类也会由于metaclass指定的type来创建类类。
"""
from django import forms

class LoginForm(forms.Form):
    name = forms.CharField()

def index(request):
    if request.method == 'GET':
        form = LoginForm()
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            pass
"""


# from wtforms import Form
# from wtforms.fields import simple
#
# # LoginForm > Form > NewBase(metaclass=FormMeta) -> BaseForm
# class LoginForm(Form):
#     name = simple.StringField()
#     pwd = simple.StringField()


############ 类及对象创建的流程 ############
"""
class MyType(type):
    def __init__(self, name, bases, dic):
        print('2 type.init')
        super().__init__(name, bases, dic)

    def __new__(cls, name, bases, dic):
        print('1 type.new')
        return super().__new__(cls, name, bases, dic)

    def __call__(self, *args, **kwargs):
        print('3. type.call')
        object = self.__new__(self,*args, **kwargs)
        object.__init__(*args, **kwargs)

class Foo(object,metaclass=MyType):
    def __init__(self):
        print('3.2 foo.init')
    def __new__(cls, *args, **kwargs):
        print('3.1 foo.new')
        return super().__new__(cls)

obj = Foo()
"""

################################ metaclass相关补充 ##############################
# class Foo(object):
#     def func(self):
#         print('foo.func')

# obj = Foo()
# obj.func()

# obj = Foo()
# Foo.func(obj)

################################ metaclass回顾 ##############################

# 1. 对象是由类创建;类是由type创建
# new_class = type('Foo',(object,),{})

# 2. metaclass指定类由那个type(泛指继承了type的类)创建。
# class MyType(type):
#     def __init__(self,*args,**kwargs):
#         print('创建Foo类')
#         super().__init__(*args,**kwargs)
#
# class Foo(metaclass=MyType):
#     pass

# 3. metaclass指定类由那个type(泛指继承了type的类)创建。
"""
class MyType(type):
    def __init__(self, name, bases, dic):
        print('2 type.init,在创建Foo类执行进行类的初始化')
        super().__init__(name, bases, dic)

    def __new__(cls, name, bases, dic):
        print('1 type.new,创建Foo类 ')
        foo_class = super().__new__(cls, name, bases, dic)
        # print(foo_class) # <class '__main__.Foo'>
        return foo_class

    def __call__(self, *args, **kwargs):
        print('3. type.call')
        object = self.__new__(self,*args, **kwargs)
        object.__init__(*args, **kwargs)

class Foo(object,metaclass=MyType):
    def __init__(self):
        print('3.2 foo.init')
    def __new__(cls, *args, **kwargs):
        print('3.1 foo.new')
        return super().__new__(cls)

# Foo是一个类,Foo是MyType类创建的对象。所以 Foo(), MyType类创建的对象 -> MyType.call
obj = Foo()
"""

# 4. 如果 某类 中指定了metaclass=MyType,则 该类及其派生类 均由MyType来创建,例如:wtforms组件中使用。
"""
object
BaseForm
NewBase -> 由FormMeta创建。
Form
LoginForm
"""
# from wtforms import Form
# from wtforms.fields import simple
#
# class LoginForm(Form):
#     name = simple.StringField()
#     pwd = simple.StringField()

# 5. 如果 某类 中指定了metaclass=MyType,则 该类及其派生类 均由MyType来创建,例如:django form组件中使用。
"""
class MyType(type):
    def __init__(self, name, bases, dic):
        print('2 type.init,在创建Foo类执行进行类的初始化')
        super().__init__(name, bases, dic)

    def __new__(cls, name, bases, dic):
        print('1 type.new,创建Foo类 ')
        foo_class = super().__new__(cls, name, bases, dic)
        # print(foo_class) # <class '__main__.Foo'>
        return foo_class

class Foo(object,metaclass=MyType):
    pass
"""
"""
...
BaseForm
temporary_class,是由 metaclass > DeclarativeFieldsMetaclass >  MediaDefiningClass > type 创建的。
Form
"""
# from django import forms
#
#
# class LoginForm(forms.Form):
#     name = forms.CharField()
#

 

posted @ 2021-07-28 21:41  我用python写Bug  阅读(84)  评论(0编辑  收藏  举报