类的高级函数

2022-12-23 Python进阶

类中的几个高级函数,它们也是类中的内置函数,通过使用它们, 会让我们在进行类开发的时候更加的顺手。

# __str__

函数的功能:默认情况下,该函数是没有任何值的。如果定义了这个函数,当我们使用 print 打印了当前实例化对象后,就会返回该函数的 return 信息。通常我们是返回一个字符串信息,作为介绍这个类的信息。

class Test(object):
    def __str__(self):
        return '这是一个测试类'

test = Test()
print(test)             # 这是一个测试类

# __getattr__

函数的功能:当调用的属性或方法不存在的时候,会返回该方法或函数的定义信息

class Test(object):
    def __getattr__(self, key):
        print('这个 key : {} 不存在'.format(key))

test = Test()
test.test                # 这个 key : test 不存在

# __setattr__

函数的功能:拦截当前类中不存在的属性和值,对它们可以进行一些业务处理。

class Test(object):
    def __setattr__(self, key, value):
        if key not in self.__dict__:
            # print(self.__dict__)				# 每一个类中都有这样一个空的字典
            self.__dict__[key] = value


test = Test()
test.name = 'Neo'
print(test.name)  # Neo

# __call__

函数的功能:本质上是将一个实例化后的类变成一个函数。

class Test(object):
    def __call__(self, *args, **kwargs):
        print('__call__ func will start')
        # print(self.__dict__)				# 每一个类中都有这样一个空的字典
        print('args is {}'.format(kwargs))

test = Test()
test(name='Neo')
上次更新: 1 年前