gpt4 book ai didi

python - Python中如何进行封装?

转载 作者:太空狗 更新时间:2023-10-29 19:30:33 25 4
gpt4 key购买 nike

这是怎么回事?从客观和功能的角度来看?

import sys

class EncapsulationClass(object):

def __init__(self):
self.privates = ["__dict__", "privates", "protected", "a"]
self.protected = ["b"]

print self.privates

self.a = 1
self.b = 2
self.c = 3
pass

def __getattribute__(self, name):
if sys._getframe(1).f_code.co_argcount == 0:
if name in self.privates:
raise Exception("Access to private attribute \"%s\" is not allowed" % name)
else:
return object.__getattribute__(self, name)
else:
return object.__getattribute__(self, name)

def __setattr__(self, name, value):
if sys._getframe(1).f_code.co_argcount == 0:
if name in self.privates:
raise Exception("Setting private attribute \"%s\" is not allowed" % name)
elif name in self.protected:
raise Exception("Setting protected attribute \"%s\" is not allowed" % name)
else:
return object.__setattr__(self, name, value)
else:
return object.__setattr__(self, name, value)


example = EncapsulationClass()

example.a = 10 # Exception: Setting private attribute "a" is not allowed
example.b = 10 # Exception: Setting protected attribute "b" is not allowed
example.c = 10 # example.c == 10

example.__dict__["privates"] # Exception: Setting protected attribute "b" is not allowed

这样做实际上有什么问题?

有没有更好的办法在Python中实现封装?

最佳答案

Python 具有封装性——您正在类里面使用它。

它没有的是访问控制,例如私有(private)和 protected 属性。但是,在 Python 中,有一种属性命名约定,通过在属性前加上一个或两个下划线来表示私有(private)属性,例如:

self._a
self.__a

单个下划线向类的用户指示属性应被视为该类的私有(private)属性,不应直接访问。

双下划线表示相同,但​​是,Python 会稍微破坏属性名称以试图隐藏它。

class C(object):
def __init__(self):
self.a = 123 # OK to access directly
self._a = 123 # should be considered private
self.__a = 123 # considered private, name mangled

>>> c = C()
>>> c.a
123
>>> c._a
123
>>> c.__a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute '__a'
>>> c._C__a
123

您可以在最后一个示例中看到名称从 __a 更改为 _C__a,尽管它仍然可以在类中作为 self.__a< 访问.

关于python - Python中如何进行封装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26216563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com