__setattr_、__getattr__、__delattr__

class F:

    def __setattr__(self, key, value):
        if key in self.__dict__:
            pass
        else:
            self.__dict__[key] = value

    def __getattr__(self, item):
        """
        对象没有item属性时才会调用这个方法

        :param item:
        :return:
        """

        return '"{}" not exists'.format(item)

    def __delattr__(self, item):
        if item in self.__dict__:
            self.__dict__.pop(item)
            print('delete "{}" successfully'.format(item))
        else:
            print('delete failed, not exist "{}"'.format(item))


f = F()

f.name = 'kai'
print(f.name)
print(f.namse)

del f.a
del f.name
kai
"namse" not exists
delete failed, not exist "a"
delete "name" successfully

你可能感兴趣的:(__setattr_、__getattr__、__delattr__)