Python 类高级用法梳理

作者: ropon 分类: Python 发布时间: 2019-08-20 09:10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/8/20 8:44
# @Author  : Ropon
# @File    : test6.py

# class Foo(object):
#     # def __iter__(self):
#     #     return iter([12, 34, 56])
#
#     def __iter__(self):
#         yield 11
#         yield 22
#         yield 33
#
#
# obj = Foo()
#
# for item in obj:
#     print(item)

# 对象可循环,要变成可迭代对象,有__iter__(self) 方法

# class Foo(object):
#     def __new__(cls, *args, **kwargs):
#         return super(Foo, cls).__new__(cls)
#         # return object.__new__(cls)
#         # return 12345
#
# obj = Foo()
# print(obj)

# __new__ 返回值决定对象是什么

# 对象由类创建,类有type创建,可通过metaclass 指定由谁创建类

# 方式一
# class Foo(object):
#     aa = 12
#
#     def func1(self):
#         return 88

# 方式二
# Foo = type('Foo', (object, ), {'aa': 12, 'func1': lambda self: 88})
#
# obj = Foo()
# print(obj.func1())
# print(Foo.aa)

# class MyType(type):
#     def __init__(self, *args, **kwargs):
#         print('创建类')
#         super(MyType, self).__init__(*args, **kwargs)
#
#     def __call__(cls, *args, **kwargs):
#         print('类实例化,通过__call__触发类的__new__ 和 __init__ 方法')
#         obj = cls.__new__(cls, *args, **kwargs)
#         cls.__init__(obj, *args, **kwargs)
#         return obj
#
# class Foo(object, metaclass=MyType):
#     ab = 333
#
#     def __init__(self):
#         pass
#
#     def __new__(cls, *args, **kwargs):
#         return super(Foo, cls).__new__(cls)
#
#     def func1(self):
#         return 888
#
# obj = Foo()
# print(obj.func1())

# 创建类时,先执行metaclass 指定的__init__ 方法
# 类实例化时,先执行metaclass 指定的__call__ 方法 触发类的__new__ 和 __init__ 方法

class Foo(object):
    cc = 66

    def __init__(self, errcode=0, errmsg='ok'):
        self.errcode = errcode
        self.errmsg = errmsg

    def func1(self):
        return 888

# print(dir(Foo))
lst = dir(Foo)
nlst = []
for item in lst:
    if not item.startswith('_'):
        nlst.append(item)
print(nlst)
obj = Foo()
print(obj.__dict__)

# dir 查看类的成员
# __dict__ 查看对象内部存储的所有属性名和属性值组成的字典

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!