今日最坑,学习super()时,跟着例子敲代码竟然出现,如此的错误。
错误原因:
super中需要填入的是子类的类名,而不是父类的类名。如果填入父类类名将报未找类名的错误。
super(子类,self).init(),继承父类init方法中参数的需要使用到该语句。
代码1
class Study:
a = 1
b = 2
def __init__ (self):
self.name = "JACK-E"
self.add = "JACK-E 学习专用类 "
class Study_english(Study):
c = 1
d = 2
def __init__ (self):
**super(Study,self).__init__()**
print(self.name,self.add)
self.name = "JACK-A"
self.add = "JACK-A 学习英语专用类"
print(self.name,self.add)
#父类名调用__dict__
print(Study.__dict__)
#子类名调用__dict__
print(Study_english.__dict__)
#父类实例对象调用 __dict__
study = Study()
print(study.__dict__)
#子类实例对象调用 __dict__
study_eng=Study_english()
print(study_eng.__dict__)
{'__module__': '__main__', 'a': 1, 'b': 2, '__init__': <function Study.__init__ at 0x000002615C0DC048>, '__dict__': <attribute '__dict__' of 'Study' objects>, '__weakref__': <attribute '__weakref__' of 'Study' objects>, '__doc__': None}
{'__module__': '__main__', 'c': 1, 'd': 2, '__init__': <function Study_english.__init__ at 0x0000026158338268>, '__doc__': None}
{'name': 'JACK-E', 'add': 'JACK-E 学习专用类 '}
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-101-b8e25084c846> in <module>
24 print(study.__dict__)
25 #子类实例对象调用 __dict__
---> 26 study_eng=Study_english()
27 print(study_eng.__dict__)
<ipython-input-101-b8e25084c846> in __init__(self)
11 def __init__ (self):
12 super(Study,self).__init__()
---> 13 print(self.name,self.add)
14 self.name = "JACK-A"
15 self.add = "JACK-A 学习英语专用类"
AttributeError: 'Study_english' object has no attribute 'name'
代码2
class Study:
a = 1
b = 2
def __init__ (self):
self.name = "JACK-E"
self.add = "JACK-E 学习专用类 "
class Study_english(Study):
c = 1
d = 2
def __init__ (self):
super(Study_english,self).__init__()
print(self.name,self.add)
self.name = "JACK-A"
self.add = "JACK-A 学习英语专用类"
print(self.name,self.add)
#父类名调用__dict__
print(Study.__dict__)
#子类名调用__dict__
print(Study_english.__dict__)
#父类实例对象调用 __dict__
study = Study()
print(study.__dict__)
#子类实例对象调用 __dict__
study_eng=Study_english()
print(study_eng.__dict__)
{'__module__': '__main__', 'a': 1, 'b': 2, '__init__': <function Study.__init__ at 0x000002615C1649D8>, '__dict__': <attribute '__dict__' of 'Study' objects>, '__weakref__': <attribute '__weakref__' of 'Study' objects>, '__doc__': None}
{'__module__': '__main__', 'c': 1, 'd': 2, '__init__': <function Study_english.__init__ at 0x000002615C164840>, '__doc__': None}
{'name': 'JACK-E', 'add': 'JACK-E 学习专用类 '}
JACK-E JACK-E 学习专用类
JACK-A JACK-A 学习英语专用类
{'name': 'JACK-A', 'add': 'JACK-A 学习英语专用类'}