zoukankan      html  css  js  c++  java
  • Python类的特点 (1):构造函数与方法

    Python中,类的特点:

     1 #encoding:utf-8
     2 class Parent(object):
     3     x=1 #x是Parent类的属性(字段)
     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 class MyClass():
    19     def printMe(self):
    20         print 'gege'
    21 
    22 if __name__=='__main__':
    23 
    24     '''类属性和实例属性的区别'''
    25     p=Parent()
    26     p.x=11
    27     print Parent.x,p.x
    28     Parent.x=5
    29     print Parent.x,p.x
    30     print '-------------------'
    31     
    32     '''子类可以通过继承获得父类的属性'''
    33     print Child1.x
    34     print '-------------------'
    35     
    36     '''观察构造函数的调用'''
    37     c1=Child1()#Child1本身没有构造函数,将调用父类的构造函数
    38     print '-------------------'
    39     c2=Child2()#Child2重写了构造函数,将调用其自身的构造函数,且不再调用父类的构造函数
    40     print '-------------------'
    41     c3=Child3()#Child2重写了构造函数,并且在构造函数内调用了父类的构造函数

    输出:

    creating Parents instance..
    1 11
    5 11
    -------------------
    5
    -------------------
    creating Parents instance..
    -------------------
    creating Child2 instance..
    -------------------
    creating Parents instance..
    creating Child3 instance..

    Python中类的方法又有怎样的特点?

     1 #encoding:utf-8
     2 class MyClass():
     3     def doPrint(self):
     4         print 'doPrint invoked..'
     5 
     6 
     7 if __name__=='__main__':
     8     doPrint()#编译不通过,提示 NameError: name 'doPrint' is not defined
     9     MyClass.doPrint()#编译通过,但运行时报错,提示 TypeError: unbound method doPrint() must be called with MyClass instance as first argument (got nothing instead)
    10     MyClass().doPrint()#正确运行,打印出 doPrint invoked..

    以上测试说明Python中的类有以下几个特点:

    1. Python也有类似Java的静态属性(类属性),但是不用static关键字修饰。那么如何区分类属性还是实例属性?参考第2条

    2. Python类中的属性若写成 "类名.属性" 形式,就是类属性,若写成"实例.属性" 形式,就是实例的属性,两者互不干扰(修改类的属性的值,不会改变实例属性的值,反之亦然)

    3. 构造函数:如果子类没有,就用父类的;子类有的,就只用子类的,不再调用父类的(这与C++不同),若想调用父类的构造函数必须显式的写成 "父类.__init__(self,其他参数)",其中的self 即子类实例自身。

    4. 没有类似Java的类方法(用static修饰),Python类中的方法必须由实例来调用(即所谓的绑定机制,方法必须和实例绑在一起才能调用),"类名.方法"这种写法,语法上没错,但不能执行。

  • 相关阅读:
    现阶段学习窘境总结(2013年6月21日-至今)
    MvcPager 分页控件
    JS 实现PDF文件打印
    json和Jsonp 使用总结(1)
    实战篇之存储过程的使用
    ASP.NET MVC5 之 客户端实现文件的下载
    WMI 技术
    PowerDesigner 的使用教程
    Rose
    对路径 obj 文件夹访问被拒绝
  • 原文地址:https://www.cnblogs.com/aaronhoo/p/5585414.html
Copyright © 2011-2022 走看看