Python类继承: dynamic attribute creation

标签 python python-3.x

我不确定我问的是否正确,但我知道你们都很聪明,能够弄清楚:)。我在压缩一些 python 类中的一些重复代码时遇到了麻烦。这是我的意思的一个例子......

class Parent:

    PATH_PROPERTIES = [ 'parent' ]

    def __init__(self, path):
        self.props = { 'parent': path }

    def getPath(self):
        return self.props['parent']


class Child(Parent):

    PATH_PROPERTIES = [ 'child' ]

    def __init__(self, path):
        self.props = { 'child': path }

    def getPath(self):
        return self.props['child']

上面是目前的情况,但我想通过做类似的事情来减少一些重复......

class Parent:
    name = 'parent'

    PATH_PROPERTIES = [ name ]

    def __init__(self, path):
        self.props = ( name: path)

    def getPath(self):
        return self.props[name] 

最后一段代码显然不起作用。我找不到任何关于 Python 能够执行类似 C++ 的宏的信息。压缩此代码的最佳方法是什么?

最佳答案

您可以使用继承:

class Parent:

    PATH_PROPERTIES = [ 'parent' ]

    def __init__(self, path):
        self.props = { self.PATH_PROPERTIES[0]: path }

    def getPath(self):
        return self.props[self.PATH_PROPERTIES[0]]


class Child(Parent):

    PATH_PROPERTIES = [ 'child' ]    


c = Child('path')
print(c.getPath())

打印

path
<小时/>

请注意,在 Python 中通常最好使用 property而不是 getter 函数:

class Parent:

    PATH_PROPERTIES = 'parent'

    def __init__(self, path):
        self.props = { self.PATH_PROPERTIES: path }

    @property
    def path(self):
        return self.props[self.PATH_PROPERTIES]


class Child(Parent):

    PATH_PROPERTIES = 'child'         

c = Child('path')
print(c.path)

还打印

path

请注意,c.path 看起来像属性查找,但由于 path 是一个属性,因此它调用修饰的函数>@属性。 该语法看起来比 c.getPath() 更好,但提供了相同的功能。有a decorator to make setters too

关于Python类继承: dynamic attribute creation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19577260/

相关文章:

python-3.x - 如何使用 Python PPTX 设置图表标题的字体大小?

python - 我想知道为什么这行得通

python - Django - 按属性将查询分为子组

python - Pandas 选择所有没有 NaN 的列

python - 我可以在 pandas 中获得一个额外的标题作为所有列顶部的名称吗

python - 如何在 csv 文件中查找元素并编辑该文件

python - 为什么我无法在 Python 中正确地将项目添加到列表中?

python - wxMessageBox 在 python 中返回什么?

python - 异步: Why is awaiting a cancelled Future not showing CancelledError?

regex - 如何减少python正则表达式中的步骤?