python中的受保护方法

Poo*_*oya 27 python oop access-modifiers

可能重复:
在python子类中将方法设为
私有Python中的私有变量和方法

如何在受保护的python类中定义一个方法,只有子类可以看到它?

这是我的代码:

class BaseType(Model):
    def __init__(self):
        Model.__init__(self, self.__defaults())


    def __defaults(self):
        return {'name': {},
                'readonly': {},
                'constraints': {'value': UniqueMap()},
                'cType': {}
        }


    cType = property(lambda self: self.getAttribute("cType"), lambda self, data:              self.setAttribute('cType', data))
    name = property(lambda self: self.getAttribute("name"), lambda self, data: self.setAttribute('name', data))
    readonly = property(lambda self: self.getAttribute("readonly"),
                        lambda self, data: self.setAttribute('readonly', data))

    constraints = property(lambda self: self.getAttribute("constraints"))

    def getJsCode(self):
        pass

    def getCsCode(self):
        pass


    def generateCsCode(self, template=None, constraintMap=None, **kwargs):
        if not template:
            template = self.csTemplate

        if not constraintMap: constraintMap = {}
        atts = ""

        constraintMap.update(constraintMap)

        for element in self.getNoneEmptyAttributes():
            if not AbstractType.constraintMap.has_key(element[0].lower()):
                continue
            attTemplate = Template(AbstractType.constraintMap[element[0].lower()]['cs'])
            attValue = str(element[1]['value'])
            atts += "%s  " % attTemplate.substitute({'value': attValue})

        kwargs.update(dict(attributes=atts))

        return template.substitute(kwargs)



class  MainClass(BaseType, Model):
    def __init__(self):
        #Only Model will initialize
        Model.__init__(self, self.__defaults())
        BaseType.__init__(self)

    def __defaults(self):
        return {'name': {},
                'fields': {'value': UniqueMap()},
                'innerClass': {'value': UniqueMap()},
                'types': {}
        }

    fields = property(lambda self: self.getAttribute("fields"))
    innerClass = property(lambda self: self.getAttribute("innerClass"))
    types = property(lambda self: self.getAttribute("types"))


    @staticmethod
    def isType(iType):
    #        return type(widget) in WidgetSelector.widgets.itervalues()
        return isinstance(iType, AbstractType)

    def addType(self, type):
        if not MainClass.isType(type):
            raise Exception, "Unknown widget type %s" % type
        self.types[type.name] = type
Run Code Online (Sandbox Code Playgroud)

我想要的只是子类BaseType看到的generateCsCode方法BaseType.

Ned*_*der 73

Python不像C++/Java/C#那样支持访问保护.一切都是公开的.座右铭是,"我们都是成年人." 记录您的课程,并坚持要求您的协作者阅读并遵循文档.

Python中的文化是以下划线开头的名称,"不要使用这些,除非你真的知道你应该这样做." 您可以选择使用下划线开始"受保护"方法.但请记住,这只是一个约定,它不会改变方法的访问方式.

以双下划线(__name)开头的名称被破坏,因此可以构建继承层次结构而不必担心名称冲突.有些人将这些用于"私有"方法,但同样,它并没有改变方法的访问方式.

最好的策略是习惯一个模型,在这个模型中,必须编写单个进程中的所有代码才能相处.

  • 答案很简单,并且已经提供:你不能在Python中. (38认同)
  • 我希望“破坏者和黑客”的评论与受保护的方法无关。如果黑客在您的进程中运行其代码,则没有任何受保护的方法可以拯救您。 (5认同)
  • @NedBatchelder`“我们是大人!”`我希望您能对破坏者和黑客说: (2认同)

Sve*_*ach 12

你不能.Python故意不支持访问控制.按照惯例,以下划线开头的方法是私有的,您应该在文档中明确说明应该使用该方法的人员.

  • 按照惯例,一个下划线被认为是受保护的,两个下划线被认为是私有的. (6认同)
  • 在PEP 8中,查看"设计继承"部分.特别是以"另一类属性"开头的段落是"子类API"的一部分(在其他语言中通常称为"受保护"**)".对我来说,该部分描述了受保护的属性.还有很多人相信[像这个人](http://radek.io/2011/07/21/private-protected-and-public-in-python/).我知道互联网上的文章永远不是证据.但是,有足够多的人同意这一点,因此根据定义是一个惯例,不是吗? (3认同)