我不确定我问的是否正确,但我知道你们都很聪明,能够弄清楚:)。我在压缩一些 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/