天天看點

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()
#