Python 常用方法 属性 元类

Python 常用 方法 属性 | 元类



1 Python 变量命名注意点

_a __a a_ __a__
防止from xx import * 导入 私有属性&&私有方法 区别于Python关键字 魔法方法 具有一定功能


2 常用魔法方法

2.1

__new__ __init__ __str__ __del__ __getattr__ __getattribute__(属性拦截器) __call__
构建方法 实例对象创建自调用 初始化对象自调用 获取对象打印信息 return返回 析构方法 对象引用计数为0 自调用 未定义的属性 调用 实例对象访问类属性&&实例属性 无论是否存在 都调用 实例对象()||类()() 调用 应用类装饰器

2.2 属性拦截器

class Test:
    def __init__(self, n):
        self.n = n
        self.n1 = 'Python'
    
    def __getattribute__(self, item):
        if item == 'n':
            return 'n属性通过测试'
        # else:
        #     return object.__getattribute__(self, item)  # 默认访问实例属性n1


t = Test('C')
print(t.n)  # C
print(t.n1)  # None 

2.3 单例设计模式

class Test:
    __n = None
    
    def __new__(cls, *args, **kwargs):
        if not cls.__n:
            cls.__n = object.__new__(cls)
        return cls.__n


a = Test()
b = Test()
print(id(a), id(b))  # 1565141236936 1565141236936


3 内置函数(常用)

3.1 内置函数可通过 dir(__builtins__) 查看


3.2 常用内置函数

range

s = [for i in range(3)]  # python3 返回可迭代对象&&python2返回一个列表对象

map

# map(func, seq1, seq2....) 根据func映射处理序列(多个) 返回一个map对象  
s = map(lambda x: x**2, [1, 2])  # <map object at 0x00000218AA401848>
print(list(s))  # >>[1, 4]

s1 = map(lambda x:x, 'string')
print(list(s1))  # >>['s', 't', 'r', 'i', 'n', 'g']


filter

# filter(func, seq)  对数据进行特定条件过滤
s = filter(lambda x: x // 2, [1, 2, 4])
print(list(s))  # >>>[2, 4]

reduce

from functools import reduce
# reduce(func, seq) 对序列数据进行重复操作
def test(x, y):
    return x*10+y
print(reduce(test, [1, 3, 5])) # 135


print(reduce(lambda x, y: x+y, [1,2,3], 5))  # 11>>>5+1--6+2--8+3


4 魔法属性

4.1

__doc__ __module__ __class__ __dict__
输出类的描述信息 >'''描述信息''' 输出对象所在的模块名 对象的父类 类&对象的属性 方法
Test.doc int.module>>>builtins 返回父类对象 {'a':xx, 'b':yy}

4.2 __slots__属性 对实例对象属性限制 对继承子类不作用

class Test:
    __slots__ = ['name']


a = Test()
a.name = 'fsh'
print(hasattr(a, 'name'))  # >>>True
a.age = 11  # 开始执行报错:AttributeError: 'Test' object has no attribute 'age'
print(hasattr(a, 'age'))


4.3 -动态语言-Python 动态添加属性&方法

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
# 动态添加属性  
a1 = Person('x', 11)
a1.sex = 'female'  # 动态添加实例属性只作用于a1实例
a2 = Person('y', 12)
# print(a2.sex)  # 报错
Person.sex = None  # 通过类对象添加属性 实现动态改变实例属性
# print(a2.sex)  # None


# 动态添加方法
def say(self, anying):
    print('%s 说了:%s' % (self.name, anying))

    
import types
a1.say = types.MethodType(say, a1)  # 实例a1动态添加实例方法say
a1.say('hello') 



5 元类

5.1 元类是所有类的顶级父类 | | 亦可用于判断对象类型 || 拦截类的创建 || 修改类


5.2 type(obj):判断类型 | obj= type('类名',(父类,),{'属性名': 属性值,’方法名‘: ’方法引用‘,.....})


5.3 元类创建类

# 方式一 type()
Test = type('Test', (), {'name': 'x'})  # 附带属性


def test(self):
    print('test.....')
    
    
Test1 = type('Test1', (Test,), {'test': test})  # 附带方法继承
print(hasattr(Test1,'test'))  # True 判断对象是否存在相应属性&方法
print(hasattr(Test1,'name'))  # True
# 方式二 添加类属性 __metaclass__ 实现自定义类(python2) 对属性&方法做---再处理
def up_attr(cls_name, cls_par, cls_atr):
    new_atr = dict()
    for k, v in cls_atr.items():
        if not k.startswith('__'):
            new_atr[k.upper()] = v
    return type(cls_name, cls_par, new_atr)


class Test(object, metaclass=up_attr):  # python3方式
    name = 'xyz'


print(hasattr(Test, 'name'))
print(hasattr(Test, 'NAME'))
# 方式三  继承type
class Test(type):
    def __new__(cls, cls_name, cls_par, cls_atr):
        new_atr = {}
        for k, v in cls_atr.items():
            if not k.startswith('__'):
                new_atr[k.upper()] = v
        return type(cls_name, cls_par, new_atr)
        # return type.__new__(cls, cls_name, cls_par, new_atr)


class Test1(object, metaclass=Test):
    abc = 'xyz'
    
    
print(hasattr(Test1, 'abc'))  # False
print(hasattr(Test1, 'ABC'))  # True

5.4 通过使用元类 可以在创建类时 进行再处理



6 英语谚语

When the world turn its back on you, you turn your back on the world! And only embrace what's next!

-若世界与你背道而驰 你无需亦步亦趋 欣然走好接下来的每一步吧

posted @ 2020-08-05 11:45  爱编程_喵  阅读(104)  评论(0)    收藏  举报
jQuery火箭图标返回顶部代码

jQuery火箭图标返回顶部代码

滚动滑动条后,查看右下角查看效果。很炫哦!!

适用浏览器:IE8、360、FireFox、Chrome、Safari、Opera、傲游、搜狗、世界之窗.