zoukankan      html  css  js  c++  java
  • python基础-4

    python面向对象

    创建类:

    使用class语句来创建一个新类,class之后为类的名称并以冒号结尾,如下实例:

    class ClassName:
       'Optional class documentation string'#类文档字符串
       class_suite  #类体

    python内置类属性(通过类名调用):

    • __dict__ : 类的属性(包含一个字典,由类的数据属性组成)

    • __doc__ :类的文档字符串

    • __name__: 类名

    • __module__: 类定义所在的模块(类的全名是'__main__.className',如果类位于一个导入模块mymod中,那么className.__module__ 等于 mymod

    • __bases__ : 类的所有父类构成元素(包含了一个由所有父类组成的元组)

    类变量在类的所有实例之间共享,通过类名来访问类变量

    类变量紧接在类名后面定义,相当于java和c++的static变量

    实例变量在__init__里定义,相当于java和c++的普通变量,通过实例来调用

    实例变量在def里通过self点运算变量名能被赋值(必须要有self),不一定非在init里,其他已被调用的方法函数里也行,类变量class里def外,通过变量名能被赋值,def里通过类对象即类名字的点运算变量名可被赋值

    >>> class test:
        count = 0;
        def __init__(self, c)://self不可以省略
            self.count = c;//实例变量,若没有self,则count是类变量
            self.__class__.count = self.__class__.count + 1;
            
    >>> a = test(3)
    >>> a.count
    3
    >>> test.count
    1
    >>> b = test(-1)
    >>> b.count
    -1
    >>> test.count
    2
    >>> 

    python对象销毁(垃圾回收):引用计数

    class Point:
       def __init( self, x=0, y=0):
          self.x = x
          self.y = y
       def __del__(self):
          class_name = self.__class__.__name__
          print class_name, "destroyed"
    
    pt1 = Point()
    pt2 = pt1
    pt3 = pt1
    print id(pt1), id(pt2), id(pt3) # 打印对象的id
    del pt1
    del pt2
    del pt3

    以上实例运行结果如下:

    3083401324 3083401324 3083401324
    Point destroyed
    

    类的继承:

    语法:

    派生类的声明,与他们的父类类似,继承的基类列表跟在类名之后,如下所示:

    class SubClassName (ParentClass1[, ParentClass2, ...]):
       'Optional class documentation string'
       class_suite

    python中继承中的一些特点:

    • 1在继承中基类的构造(__init__()方法)不会被自动调用,它需要在其派生类的构造中亲自专门调用。(子类若实现了这个方法则覆盖了父类的初始化函数,否则默认调用父类的__init__方法)

    • 2在调用基类的方法时,需要加上基类的类名前缀,且需要带上self参数变量即父类实例作为第一个参数。区别于在类中调用普通函数时并不需要带上self参数

    • 3Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。(先在本类中查找调用的方法,找不到才去基类中找)。

    调用父类函数有以下方法:

    class A(object):
        def method(self, arg):  
            pass
    
    class B(A):
        def method(self, arg):
    #        A.method(self,arg)                # 1
    #        super(B, self).method(arg)    #在类外使用时,将self替换为B类实例,类里面使用时,运用self即可,method中不必加self
            super().method(arg)                #python3中的用法

    1.直接写类名调用

    2.用 super(方法调用。

    3.在类定义中调用本类的父类方法,可以直接 super().method(arg).

    class Parent:        # 定义父类
       parentAttr = 100
       def __init__(self):
          print "Calling parent constructor"
    
       def parentMethod(self):
          print 'Calling parent method'
    
       def setAttr(self, attr):
          Parent.parentAttr = attr//给类变量赋值
    
       def getAttr(self):
          print "Parent attribute :", Parent.parentAttr
    
    class Child(Parent): # define child class
       def __init__(self):
          print "Calling child constructor"
    
       def childMethod(self):
          print 'Calling child method'
    
    c = Child()          # 实例化子类
    c.childMethod()      # 调用子类的方法
    c.parentMethod()     # 调用父类方法
    c.setAttr(200)       # 再次调用父类的方法
    c.getAttr()          # 再次调用父类的方法

    super(type[, object-or-type])

      Return the superclass of type. If the second argument is omitted the super object
      returned is unbound. If the second argument is an object, isinstance(obj, type)
      must be true. If the second argument is a type, issubclass(type2, type) must be
      true. super() only works for new-style classes.

    Python 2中的classobj不算做一种type,所以定义父类时需要继承自object

    方法重写:

    如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法

    运算符重载:

    class Vector:
       def __init__(self, a, b):
          self.a = a
          self.b = b
    
       def __str__(self):
          return 'Vector (%d, %d)' % (self.a, self.b)
       
       def __add__(self,other):
          return Vector(self.a + other.a, self.b + other.b)//注意:通过self来访问同一个类中的变量
    
    v1 = Vector(2,10)
    v2 = Vector(5,-2)
    print v1 + v2
    

    以上代码执行结果如下所示:

    Vector(7,8)
    

    python 的重载主要包括方法重载和运算符重载。

    1.python 方法重载: 其他的语言一般对于方法重载的话,主要是根据参数的类型不同或者是数量不同来区分同名的方法。而python则比较特殊,它本身是动态语言,方法的参数是 没有类型的,当调用传值的时候才确定参数的类型,故对参数类型不同的方法无需考虑重载对参数数量不同的方法,则(大多数情况下)可以采用参数默认值来实现。

    比如你可以定义函数的默认值:

    def info(x,y,z=1):

         pass

    2.python 运算符重载: 在 Python中,每一个类都默认内置了所有可能的运算符方法,只要重写这个方法,就可以实现针对该运算符的重载。

    python中实现数据隐藏很简单,不需要在前面加什么关键字,只要把类变量名或成员函数前面加两个下划线即可实现数据隐藏的功能,这样,对于类的实例 来说,其变量名和成员函数是不能使用的,对于其类的继承类来说,也是隐藏的,这样,其继承类可以定义其一模一样的变量名或成员函数名,而不会引起命名冲 突。

    Python不允许实例化的类访问隐藏数据,但你可以使用object._className__attrName访问属性

    class JustCounter:
        __secretCount = 0
        def count(self):
            self.__secretCount += 1
            print self.__secretCount
    
    counter = JustCounter()
    counter.count()
    counter.count()
    print counter._JustCounter__secretCount

     

  • 相关阅读:
    SQL Server 2008数据库镜像+故障转移集群原理摘自网络
    AHCI和IDE区别,和在目前系统中设置 AHCI 摘自网络
    中国计算机技术职业资格网(软考 官方 官网)
    第十一节 导出Excel 简单
    第五章 IF语句与逻辑运算符 简单
    第十一节 10图片权限控制 简单
    第四章 C++数据类型 简单
    第二章 从一个最简短的C++程 简单
    php 解析xml文件 简单
    第十一节 6HttpHandler案例 简单
  • 原文地址:https://www.cnblogs.com/ljygoodgoodstudydaydayup/p/4216669.html
Copyright © 2011-2022 走看看