首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >python中的Protected方法

python中的Protected方法
EN

Stack Overflow用户
提问于 2012-07-14 19:28:52
回答 2查看 48.6K关注 0票数 38

可能重复:

Making a method private in a python subclass

Private Variables and Methods in 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

我只想让BaseType的子类看到BaseTypegenerateCsCode方法。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-07-14 19:33:27

Python不像C++/Java/C#那样支持访问保护。一切都是公开的。座右铭是,“我们都是成年人了。”记录你的课程,并坚持让你的合作者阅读并遵循文档。

Python中的文化是,以下划线开头的名称意味着“除非您真正知道应该使用这些名称,否则不要使用它们。”您可以选择以下划线开始您的“受保护”方法。但请记住,这只是一个约定,它不会改变方法的访问方式。

以双下划线(__name)开头的名称被破坏,因此可以构建继承层次结构,而无需担心名称冲突。有些人将它们用于“私有”方法,但同样,它不会改变方法的访问方式。

最好的策略是习惯于这样一种模型,在这种模型中,单个进程中的所有代码都必须编写才能顺利进行。

票数 95
EN

Stack Overflow用户

发布于 2012-07-14 19:30:38

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

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11483366

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档