码迷,mamicode.com
首页 > 编程语言 > 详细

Python类的特点

时间:2016-06-14 20:57:14      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:

Python中,类的特点:

 1 #encoding:utf-8
 2 class Parent(object):
 3     x=1
 4     def __init__(self):
 5         print creating Parents instance..
 6         
 7 class Child1(Parent):
 8     pass
 9 
10 class Child2(Parent):
11     def __init__(self):
12         print creating Child2 instance..
13         
14 class Child3(Parent):
15     def __init__(self):
16         Parent.__init__(self)#若不调用这一行,将不执行父类的构造函数
17         print creating Child3 instance..
18 
19 if __name__==__main__:
20 
21     #对于属性:子类有的就用子类自己的 ,子类没有的就从父类找. 对于构造函数:如果子类没有就用父类的,子类有的,就只用子类的,不再调用父类的,如Child2
22     print Parent.x,Child1.x,Child2.x
23     Child1.x=2
24     print Parent.x,Child1.x,Child2.x
25     Parent.x=3
26     print Parent.x,Child1.x,Child2.x
27 
28     #类属性和实例属性的区别
29     p=Parent()
30     p.x=11
31     print Parent.x,p.x
32     
33     #临时增加类的属性也可以,并且可以实例化继承
34     Child2.y=10
35     print Child2.y
36     c2=Child2()
37     print c2.y,c2.x
38     
39     c3=Child3()

 

输出:

1 1 1
1 2 1
3 2 3
creating Parents instance..
3 11
10
creating Child2 instance..
10 3
creating Parents instance..
creating Child3 instance..

 

Python类的特点

标签:

原文地址:http://www.cnblogs.com/aaronhoo/p/5585414.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!