如何在Python中封装? [英] How to do encapsulation in Python?

查看:114
本文介绍了如何在Python中封装?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是怎么了?从目标和功能的角度来看?

What's wrong with this? From objective, and functional standpoints?

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

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

What would actually be wrong with doing something like this?

有没有更好的方法可以在Python中实现封装?

Is there any better way to achieve encapsulation in Python?

推荐答案

Python具有封装功能-您正在类中使用它。

Python has encapsulation - you are using it in your class.

它的功能没有访问控制,例如私有和受保护的属性。但是,在Python中,有一个属性命名约定,通过在属性前面加上一个或两个下划线来表示私有属性,例如:

What it doesn't have is access control such as private and protected attributes. However, in Python, there is an attribute naming convention to denote private attributes by prefixing the attribute with one or two underscores, e.g:

self._a
self.__a 

单个下划线表示课程的用户

A single underscore indicates to the user of a class that an attribute should be considered private to the class, and should not be accessed directly.

双下划线表示相同的含义,但是Python会将属性名称修改为

A double underscore indicates the same, however, Python will mangle the attribute name somewhat to attempt to hide it.

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 访问。 code>。

You can see in the last example that the name was changed from __a to _C__a, although it is still accessible within the class as self.__a.

这篇关于如何在Python中封装?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆