首页 > 解决方案 > 为什么可以在 Python 的父类中调用子属性,最佳实践是什么?

问题描述

我猜这段代码不应该工作,但它可以工作:

class Parent():
    def print_child(self):
        print(self.child_attr)

class Child(Parent):
    child_attr = "Some text goes here"

child = Child()
child.print_child()

那么下一个问题:最佳实践是什么?

  1. 保持原样(这似乎不是一个好主意)

  2. 定义父类:

    类父():

    child_attr = None
    
    def print_child(self):
    
        print(self.child_attr)
    
  3. 定义父类:

    类父():

    def print_child(self, child_attr):
    
        print(child_attr)
    

标签: python

解决方案


推荐阅读