gpt4 book ai didi

python - python中的 protected 方法

转载 作者:IT老高 更新时间:2023-10-28 22:16:26 33 4
gpt4 key购买 nike

Possible Duplicate:
Making a method private in a python subclass
Private Variables and Methods in Python

如何在 protected 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 方法。

最佳答案

Python 不像 C++/Java/C# 那样支持访问保护。一切都是公开的。座右铭是,“我们在这里都是成年人。”记录您的类(class),并坚持让您的合作者阅读并遵守文档。

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

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

最好的策略是适应一个模型,即必须编写单个进程中的所有代码才能相处。

关于python - python中的 protected 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11483366/

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