我需要编写十几个仅在变量上有所不同的类,这对于类的稳定工作至关重要。没有这些变量,类就无法工作,并且更改变量会破坏它们。我写了一个代码来创建相应的 metaclss:
from abc import ABCMeta, abstractmethod, abstractproperty
import re
def get_field_protector(*names):
def check_attributes(cls):
for t in names:
if not hasattr(cls, t):
raise Exception('Abstract field "{0}" have to be defined'.format(t))
def decorate_new_method(inp_method, class_name):
def inner(cls, *args, **kwargs):
if cls.__new__.decorated==class_name:
check_attributes(cls)
return inp_method(cls, *args, **kwargs)
return inner
class result_protector(ABCMeta):
def __setattr__(self, name, value):
if name in names:
raise Exception("Read only class attribute!")
super(self.__class__, self).__setattr__(name, value)
def __delattr__(self, name):
if name in names:
raise Exception("Read only class attribute!")
super(self.__class__, self).__delattr__(name)
def __init__(self, name, bases, attributes):
super(self.__class__, self).__init__(name, bases, attributes)
if not hasattr(self.__new__, 'decorated'):
self.__new__=decorate_new_method(self.__new__, name)
self.__new__.decorated=name
return result_protector
在我开始使用像这样的类之前,它工作得很好:
class test(object, metaclass=get_field_protector("essential_field")):
essential_field="some_value"
def __init__(self, val):
self.val=val
当我尝试创建此类时,我收到:
>>> test(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/media/bykov/9016-4EF8/main_architecture.py", line 13, in inner
return inp_method(cls, *args, **kwargs)
TypeError: object() takes no parameters
最佳答案
布鲁诺的评论是正确的。在 Python 中,您不“保护”父类的属性,您只需用两个前缀下划线命名它。在您的示例中 __essential_field
。这意味着将它留给任何后代。
关于python - 如何在 Python 类中制作抽象的 protected 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52090553/