首页 > 技术文章 > Python继承的一个笔记

birds-zhu 2019-07-16 16:03 原文

 1 class Post():
 2 
 3     def __init__(self):
 4         self.title = 'org'
 5         self.__decodeTitle();
 6 
 7   
 8     def __decodeTitle(self):
 9        self.title = "title1";
10        
11 class Post2(Post):
12 
13     def __init__(self):
14         Post.__init__(self);
15     def __decodeTitle(self):
16        self.title = "title2";
17        
18 post = Post()
19 print(post.title)
20 
21 post2 = Post2()
22 print(post2.title)

运行结果:

title1

title1

熟悉C#程序的我,这段程序给我造成深深的困扰.第二个输出title1,岂不是python中继承多态的特点没法使用??????

后来,我才发现是我多虑了.

 1 class Post():
 2 
 3     def __init__(self):
 4         self.title = 'org'
 5         self.decodeTitle();
 6 
 7   
 8     def decodeTitle(self):
 9        self.title = "title1";
10        
11 class Post2(Post):
12 
13     def __init__(self):
14         Post.__init__(self);
15     def decodeTitle(self):
16        self.title = "title2";
17        
18 post = Post()
19 print(post.title)
20 
21 post2 = Post2()
22 print(post2.title)

这样就会输出

title1

title2.

我的理解就是 __decodeTitle这个方法是私有的,根本不能继承下来.

我写这段代码的时候哦,用的记事本些的,没有报错.没有警告,所以让我困惑了好久.

我不知道其他的编译器遇到这种会不会有提示什么的.

推荐阅读