在Python中,描述符是一種具有特殊方法的類,可以用來控制對類屬性的訪問。要實現權限控制,你可以在描述符類中定義__get__()
、__set__()
和__delete__()
方法。以下是一個簡單的例子,展示了如何使用描述符進行權限控制:
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" # 成功修改數據
print(obj._data) # 輸出: new_secret
obj2 = MyClass("secret", "read")
print(obj2._data) # 輸出: secret
obj2._data = "new_secret" # 拋出 PermissionError
在這個例子中,我們創建了一個名為PermissionDescriptor
的描述符類,它根據給定的權限來控制對類屬性的訪問。我們還創建了一個名為MyClass
的類,它使用PermissionDescriptor
來控制對_data
屬性的訪問。當我們嘗試訪問、修改或刪除_data
屬性時,會根據_permission
屬性的值來決定是否允許操作。