Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从(父类的)方法中调用属性?_Python_Python 3.x_Class_Oop - Fatal编程技术网

Python 如何从(父类的)方法中调用属性?

Python 如何从(父类的)方法中调用属性?,python,python-3.x,class,oop,Python,Python 3.x,Class,Oop,根据这里的代码,我试图从父类Elec_eng in child class telecoms_check方法中调用属性branch_name: class Elec_eng: def __init__(self): print("This is Electrical Engineering main class") def sub_branch(self, branch_num): self.branch_name = branch_num class

根据这里的代码,我试图从父类Elec_eng in child class telecoms_check方法中调用属性branch_name:

class Elec_eng:
   def __init__(self):
       print("This is Electrical Engineering main class")
   def sub_branch(self, branch_num):
       self.branch_name = branch_num

class Telecoms(Elec_eng):
   def telecoms_check(self):
       if self.branch_name == 1 :
            print("True")
       else:
            print("False")

E = Elec_eng()
T = Telecoms()
E.sub_branch(1)
现在,当我想检查telecoms\u check method>>T.telecoms\u check时,我期望得到真实的输出,但我得到了以下结果:

'Telecoms' object has no attribute 'branch_name'

有什么问题?我该怎么解决呢?用超级方法?如何创建?

您创建了两个不同的实例,但只为其中一个实例分配了分支名称。要使代码片段的行为像您正在描述的一样,您必须将其修改为

>>> T = Telecoms()
>>> T.sub_branch(1)
>>> T.telecoms_check()
True

谢谢你有用的回答。 我的目的是检查父类方法已经指定的属性值,我不想使用>>>t.sub_branch1,我只使用>>>E.sub_branch1 最后,我找到了一个解决方案,将>>>Elec_eng.branch_name=branch_num添加到代码中:

class Elec_eng:
   def __init__(self):
       print("This is Electrical Engineering main class")
   def sub_branch(self, branch_num):
       self.branch_name = branch_num
       Elec_eng.branch_name = branch_num

class Telecoms(Elec_eng):
   def telecoms_check(self):
       if self.branch_name == 1 :
            print("True")
       else:
            print("False")

E = Elec_eng()
T = Telecoms()
E.sub_branch(1)
然后:

输出:

True

您没有调用t.sub_branch方法,这解释了为什么没有创建实例属性branch_name。我希望输出为真,为什么?您希望self.branch\u name值来自哪里?
True