Python 访问父类中的子类属性是一个好主意吗
我用JAVA作为第一语言学习了OOP原则,然后我转向Python,所以这个特性对我来说有点奇怪,虽然在很多情况下很有用 然而,我想知道这是否真的是明智的 下面将给出JAVA中的错误,因为您无法访问父类中的子类的属性Python 访问父类中的子类属性是一个好主意吗,python,class,inheritance,attributes,Python,Class,Inheritance,Attributes,我用JAVA作为第一语言学习了OOP原则,然后我转向Python,所以这个特性对我来说有点奇怪,虽然在很多情况下很有用 然而,我想知道这是否真的是明智的 下面将给出JAVA中的错误,因为您无法访问父类中的子类的属性 class parent(object): def print_x(self): print self.x class child(parent): x = 10 child().print_x() PEP8在这种情况下也会发出警告: 类“pa
class parent(object):
def print_x(self):
print self.x
class child(parent):
x = 10
child().print_x()
PEP8在这种情况下也会发出警告:
类“parent”的未解析属性引用“x”
在我个人看来,代码遍历和调试有点问题。也许这是一个依赖注入更合适的地方(组合与继承)。一个深入到“孩子”身上的“父母”充其量也值得怀疑 我们来点更大致的:
class Container(object):
def __init__(self, child_instance):
self.child = child_instance
def print_x(self):
print self.child.x
class Child(object):
def __init__(self, x):
self.x = x
child = Child(10)
parent = Container(child)
parent.print_x()
在很多情况下,组合代替继承有很多优点,比如这一个,我强烈建议您研究它们。也许这是一个依赖注入更合适的地方(组合与继承)。一个深入到“孩子”身上的“父母”充其量也值得怀疑 我们来点更大致的:
class Container(object):
def __init__(self, child_instance):
self.child = child_instance
def print_x(self):
print self.child.x
class Child(object):
def __init__(self, x):
self.x = x
child = Child(10)
parent = Container(child)
parent.print_x()
在很多情况下,用组合代替继承有很多优点,比如这一个,我强烈建议您研究它们。作为一种更干净的方法
class Parent(object):
@property
def x(self):
raise NotImplementedError
def print_x(self):
print self.x
class Child(Parent):
x = 10
更干净的方法是
class Parent(object):
@property
def x(self):
raise NotImplementedError
def print_x(self):
print self.x
class Child(Parent):
x = 10
因为您可以自己实例化父级,这会产生错误,是的,这是有问题的。Python只是比Java更具动态性,在编译时不会检查这一点。由于与Java中相同的原因,它仍然是不好的代码。因为您可以自己实例化parent
,这会产生错误,是的,这是有问题的。Python只是比Java更具动态性,在编译时不会检查这一点。由于与Java中相同的原因,它仍然是糟糕的代码。