提问人:Marcin Tamiński 提问时间:9/20/2023 最后编辑:Marcin Tamiński 更新时间:9/20/2023 访问量:89
在 Python 类中创建私有属性
Making private attributes in Python classes
问:
我想将私有属性的访问限制为仅对选定的方法。
我的意思是我不希望公共类包含私有属性。 这意味着,无论哪种方式,都需要有另一个类来保存这些属性。 虽然,仅仅将公共和私人课程分开并不能提供直接访问。 除非你自己绑定它们。
考虑到上述情况,我制作了工作原型。
基地:
# Auto-binding of private classes to public classes.
class RemoteMeta(type):
# Access to private classes via public class-names.
_classes = { }
def __new__(cls, name, bases, namespace, **kwargs):
rv = type.__new__(cls, name, bases, namespace, **kwargs)
if bases[0] is not object: # Ignore 'Remote' class.
# Access to private class-instances via public class-instances.
rv._instances = { }
# Add private class reference.
cls._classes[name[1:]] = rv
return rv
def __getattr__(cls, name):
# Since attribute is not present in private class,
# look for it in public class.
return getattr(cls._cls, name)
# Auto-binding of public instances to private instances.
# Auto-binding of private instances to public instances.
class Remote(object, metaclass=RemoteMeta):
def __new__(cls, inst, *args, **kwargs):
if cls is Remote:
detail = "'{}' class is not meant to be used directly".format(cls.__name__)
raise TypeError(detail)
v = object.__new__(cls)
# ???
v.__init__(*args, **kwargs)
# Access to public instance from private instance.
v._self = inst
# Add private instance reference.
cls._instances[inst] = v
def __getattr__(self, name):
# Since attribute is not present in private instance,
# look for it in public instance.
return getattr(self._self, name)
# Auto-binding of public classes to private classes.
class PublicMeta(type):
def __new__(cls, name, bases, namespace, **kwargs):
rv = type.__new__(cls, name, bases, namespace, **kwargs)
if bases[0] is not object: # Ignore 'Public' class.
# Access to public class from private class.
Remote._classes[name]._cls = rv
return rv
# Auto-creating of private instances for each new public instance.
class Public(object, metaclass=PublicMeta):
def __new__(cls, *args, **kwargs):
rv = object.__new__(cls)
if cls is Public:
detail = "'{}' class is not meant to be used directly".format(cls.__name__)
raise TypeError(detail)
# Create private instance.
Remote._classes[cls.__name__](rv, *args, **kwargs)
return rv
描述 符:
class RemoteClassMethod:
[...]
return self.method(
Remote._classes[owner.__name__],
*args, **kwargs
)
[...]
class RemoteInstanceMethod:
[...]
return self.method(
Remote._classes[owner.__name__]._instances[inst],
*args, **kwargs
)
[...]
class RemoteProperty:
[...]
return self.fget(
Remote._classes[owner.__name__]._instances[inst]
)
[...]
给定的代码是实现这种事情的有效方法吗?
我的意思是,有什么严重的缺点吗? 或者有更好的方法可以做到这一点吗?
答: 暂无答案
评论