Python描述符怎樣進(jìn)行權(quán)限控制

小樊
83
2024-10-30 16:05:26

在Python中,描述符是一種具有特殊方法的類,可以用來(lái)控制對(duì)類屬性的訪問(wèn)。要實(shí)現(xiàn)權(quán)限控制,你可以在描述符類中定義__get__()、__set__()__delete__()方法。以下是一個(gè)簡(jiǎn)單的例子,展示了如何使用描述符進(jìn)行權(quán)限控制:

class PermissionDescriptor:
    def __init__(self, permission):
        self.permission = permission

    def __get__(self, instance, owner):
        if self.permission == "read":
            return instance._data if hasattr(instance, "_data") else None
        elif self.permission == "write":
            return instance._data if hasattr(instance, "_data") else None
        elif self.permission == "delete":
            return instance._data if hasattr(instance, "_data") else None
        else:
            raise PermissionError("Invalid permission")

    def __set__(self, instance, value):
        if self.permission == "write":
            instance._data = value
        else:
            raise PermissionError("Invalid permission")

    def __delete__(self, instance):
        if self.permission == "delete":
            del instance._data
        else:
            raise PermissionError("Invalid permission")

class MyClass:
    def __init__(self, data, permission):
        self._data = data
        self._permission = permission

    def __setattr__(self, key, value):
        if key == "_data" or key == "_permission":
            super().__setattr__(key, value)
        else:
            descriptor = getattr(self, f"_{key}", None)
            if descriptor and descriptor.permission == self._permission:
                super().__setattr__(key, value)
            else:
                raise PermissionError("Permission denied")

# 示例
obj = MyClass("secret", "write")
print(obj._data)  # 輸出: secret
obj._data = "new_secret"  # 成功修改數(shù)據(jù)
print(obj._data)  # 輸出: new_secret

obj2 = MyClass("secret", "read")
print(obj2._data)  # 輸出: secret
obj2._data = "new_secret"  # 拋出 PermissionError

在這個(gè)例子中,我們創(chuàng)建了一個(gè)名為PermissionDescriptor的描述符類,它根據(jù)給定的權(quán)限來(lái)控制對(duì)類屬性的訪問(wèn)。我們還創(chuàng)建了一個(gè)名為MyClass的類,它使用PermissionDescriptor來(lái)控制對(duì)_data屬性的訪問(wèn)。當(dāng)我們嘗試訪問(wèn)、修改或刪除_data屬性時(shí),會(huì)根據(jù)_permission屬性的值來(lái)決定是否允許操作。

0