在 Python 类中创建私有属性

Making private attributes in Python classes

提问人:Marcin Tamiński 提问时间:9/20/2023 最后编辑:Marcin Tamiński 更新时间:9/20/2023 访问量:89

问:

我想将私有属性的访问限制为仅对选定的方法。

我的意思是我不希望公共类包含私有属性。 这意味着,无论哪种方式,都需要有另一个类来保存这些属性。 虽然,仅仅将公共和私人课程分开并不能提供直接访问。 除非你自己绑定它们。

考虑到上述情况,我制作了工作原型。

基地:

# 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]
        )
    [...]

给定的代码是实现这种事情的有效方法吗?

我的意思是,有什么严重的缺点吗? 或者有更好的方法可以做到这一点吗?

Python 属性 私有

评论

0赞 Karl Knechtel 9/20/2023
我们在这里不进行代码审查;“这是实现 X 的有效方法吗?”对于我们的标准来说,这不是一个合适的具体问题。
1赞 Peilonrayz 9/20/2023
@KarlKnechtel “还有没有办法修复'RemoteProperty'描述符?”代码审查不会修复损坏的代码。
0赞 Karl Knechtel 9/20/2023
@Peilonrayz 这一点很好。这里有两个独立的问题;你突出显示的那个可能在这里的主题,如果它是 a) 自己问的和 b) 正确指定(为了“修复”某些东西,我们必须确切地了解它有什么问题,以及当它被使用时应该发生什么)。
0赞 Marcin Tamiński 9/20/2023
@KarlKnechtel 我删掉了不相关的代码。我已经移出了第二个问题来链接

答: 暂无答案