Ricardo

python __new__

阅读时长: 1 分钟

原文链接

Python
 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
32
33
34
35
class Test:
    def __new__(cls):
        print('__new__')
        return object().__new__(cls)

    def __init__(self):
        print('__init__')


test = Test()


class SingletonObject:
    def __new__(cls, *args, **kwargs):
        if not hasattr(SingletonObject, "_instance"):
            SingletonObject._instance = object.__new__(cls)
        return SingletonObject._instance

    def __init__(self):
        pass


singleton = SingletonObject()
print(singleton.__dict__)


class NonZero(int):
    def __new__(cls, value):
        return super().__new__(cls, value) if value != 0 else None


res = NonZero(0)
print('res 0', res)
res1 = NonZero(1)
print('res 1', res1)

https://www.cnblogs.com/techflow/p/13156361.html

https://changchen.me/blog/20201122/metaclass-with-django-orm/

实战演示 https://segmentfault.com/a/1190000004426130

Python
 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
32
33
34
35
36
37
38
sensitive_words_list = ['asshole', 'fuck', 'shit']


def detect_sensitive_words(string):
    """检测敏感词汇"""
    # words_detected = filter(lambda word: word in string.lower(), sensitive_words_list)
    words_detected = None
    for item in sensitive_words_list:
        if item in string.lower():
            words_detected = True

    if words_detected:
        raise NameError('Sensitive words {0} detected in the string "{1}".'.format(words_detected, string))


class CleanerMeta(type):

    def __new__(mcs, class_name, bases, attrs):
        detect_sensitive_words(class_name)  # 检查类名
        # map(detect_sensitive_words, attrs.iterkeys())  # 检查属性名

        print("Well done! You are a polite coder!")  # 如无异常,输出祝贺消息

        return super(CleanerMeta, mcs).__new__(mcs, class_name, bases, attrs)
        # 重要!这行一定不能漏!!这回调用内建的类构造器来构造类,否则定义好的类将会变成 None


class APIBase(metaclass=CleanerMeta):
    pass


class ImAGoodBoy(APIBase):
    a_polite_attribute = 1
class FuckMyBoss(APIBase):

    pass

# detect_sensitive_words('avc')
comments powered by Disqus
记录自己
Built with Hugo
主题 Stack 由 Jimmy 设计