在Python中,
_name
是受保护的,而__name
是私有的
是否可以使用装饰器为类实现访问修饰符?怎么办?
功能应该类似于下面的代码:
class A:
def public_func(self):
self.protected_func() # Runs without warning and error (Because is called in the owner class)
self.private_func() # Runs without warning and error (Because is called in the owner class)
@protected
def protected_func(self):
print('protected is running')
self.private_func() # Runs without warning and error (Because is called in the owner class)
@private
def private_func(self):
print(f'private is running')
a = A()
a.public_func() # Runs without any warning and error (Because has no access modifier)
a.protected_func() # Runs with protected warning
a.private_func() # Raises Exception
这个问题的想法是可访问的私有函数,如下所示:
class A:
def __private_func(self):
print('private is running')
a = A()
a._A__private_function()
如果我们用
private
定义decorator
,那么就不必用__name
定义它。
所以 _A__private_function
将不存在,并且私有函数在所有者类之外确实不是不可访问的。
你可以这样尝试
def protected(func):
def wrapper(self, *args, **kwargs):
if not func.__name__.startswith('_'):
print(f"Warning: {func.__name__} is not marked as protected.")
return func(self, *args, **kwargs)
return wrapper
def private(func):
def wrapper(self, *args, **kwargs):
if not func.__name__.startswith('__'):
raise Exception(f"{func.__name__} is private and cannot be accessed directly.")
return func(self, *args, **kwargs)
return wrapper
class A:
def public_func(self):
self.protected_func()
self.private_func()
@protected
def protected_func(self):
print('protected is running')
self.private_func()
@private
def private_func(self):
print(f'private is running')
a = A()
a.public_func() # Runs without any warning or error (Because it has no access modifier)
a.protected_func() # Runs with a protected warning
a.private_func() # Raises Exception
# Accessing private function using name mangling
a._A__private_func() # Runs without any warning or error