在Python中,如何在父类中访问子类的属性(在不同的文件中)

2024-04-27 17:39:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我在(class1.py)上的父类

import class2
from class2 import *
class Parent:        # define parent class
   parentAttr = 100
   def __init__(self):
      print "Calling parent constructor"

   def parentMethod(self):
      print 'Calling parent method'

   def setAttr(self, attr):
      Parent.parentAttr = attr

   def getAttr(self):
      print "Parent attribute :", Parent.parentAttr

我的孩子在(class2.py)上课

^{pr2}$

我想在parent中使用变量XYZ班级。还有家长在班上也能帮我吗?在


Tags: frompyimportselfdefclassparentattr
1条回答
网友
1楼 · 发布于 2024-04-27 17:39:22

删除

import class2

class1.py将XYZ变量放入class1。在

此外,我建议您尽量使用组合而不是继承。如果您想了解一些关于子类的知识,请将相应的方法添加到接口中。在

还应为:"Head First Object-Oriented Analysis and Design"

相关问题 更多 >