zoukankan      html  css  js  c++  java
  • python类的使用

    下面是一个员工类的创建及类对象的创建实例:

    #!/usr/bin/python 

    # -*- coding: UTF-8 -*-

    class Employee: empCount = 0 def __init__(self,name,salary): #构造函数 self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d " % Employee.empCount def displayEmployee(self): print "Name:" , self.name, ",Salary: ", self.salary emp1 = Employee("yuan", 3000) emp2 = Employee("qiang",4000) #添加属性 emp1.age = 7 emp2.age = 8 #删除对象emp1的属性 #del emp1.age emp2.displayEmployee() print "Total emploeey %d" % Employee.empCount print "emp1 is %d years old" %emp1.age

    #python内置类属性 print "Employee.__doc__:",Employee.__doc__ print "Employee.__name__:",Employee.__name__ print "Employee.__module__:",Employee.__module__ print "Employee.__bases__:",Employee.__bases__ print "Employee.__dict__:",Employee.__dict__

     执行结果:

    Name: yuan ,Salary:  3000
    Name: qiang ,Salary:  4000
    Total emploeey 2
    emp1 is 7 years old
    Employee.__doc__: None
    Employee.__name__: Employee
    Employee.__module__: __main__
    Employee.__bases__: ()
    Employee.__dict__: {'__module__': '__main__', 'displayCount': <function displayCount at 0x00000000035184A8>, 'empCount': 2, 'displayEmployee': <function displayEmployee at 0x0000000003518518>, '__doc__': None, '__init__': <function __init__ at 0x0000000003518438>} 
    • empCount 变量是一个类变量,它的值将在这个类的所有实例之间共享。你可以在内部类或外部类使用 Employee.empCount 访问。

    • 第一种方法__init__()方法是一种特殊的方法,被称为类的构造函数或初始化方法,当创建了这个类的实例时就会调用该方法

    • self 代表类的实例,self 在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数。

    • Python内置类属性

    • __dict__ : 类的属性(包含一个字典,由类的数据属性组成)
    • __doc__ :类的文档字符串
    • __name__: 类名
    • __module__: 类定义所在的模块(类的全名是'__main__.className',如果类位于一个导入模块mymod中,那么className.__module__ 等于 mymod)
    • __bases__ : 类的所有父类构成元素(包含了一个由所有父类组成的元组)

    析构函数

    析构函数 __del__ ,__del__在对象销毁的时候被调用,当对象不再被使用时,__del__方法运行:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    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 ,"销毁"
    
    pt1 = Point()
    pt2 = pt1   #引用
    pt3 = pt1
    print id(pt1),id(pt2),id(pt3) #打印出对象的ID
    #调用析构函数进行对象的销毁
    del pt1
    del pt2
    del pt3
    

     执行结果:

    45331272 45331272 45331272
    Point 销毁
    

     注意通常你需要在单独的文件中定义一个类, 

    类的继承 

      面向对象的编程带来的主要好处之一是代码的重用,实现这种重用的方法之一是通过继承机制。继承完全可以理解成类之间的类型和子类型关系。

    需要注意的地方:继承语法 class 派生类名(基类名)://... 基类名写在括号里,基本类是在类定义的时候,在元组之中指明的。

      在python中继承中的一些特点:

    • 1:在继承中基类的构造(__init__()方法)不会被自动调用,它需要在其派生类的构造中亲自专门调用。
    • 2:在调用基类的方法时,需要加上基类的类名前缀,且需要带上self参数变量。区别在于类中调用普通函数时并不需要带上self参数
    • 3:Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。(先在本类中查找调用的方法,找不到才去基类中找)。

    如果在继承元组中列了一个以上的类,那么它就被称作"多重继承" 。

      下面一个类的继承实例:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-

    class Parent: parentAttr = 100 def __init__(self): print "调用父类构造函数" def parentMethod(self): print "调用父类方法" def setAttr(self,attr): Parent.parentAttr = attr def getAttr(self): print "父类属性:",Parent.parentAttr def aa(self): print "调用父类aa" class Child(Parent): def __init__(self): print "调用子类构造函数" def childMethod(self): print "调用子类方法" def aa(self): print "调用子类aa" c = Child() #实例化子类 c.childMethod() c.parentMethod() c.setAttr(200) c.getAttr() c.aa()

    执行结果:

    调用子类构造函数
    调用子类方法
    调用父类方法
    父类属性: 200
    调用子类aa
    

     多类继承 

    class A:        # 定义类 A
    .....
    
    class B:         # 定义类 B
    .....
    
    class C(A, B):   # 继承类 A 和 B
    

    你可以使用issubclass()或者isinstance()方法来检测。

    • issubclass() - 布尔函数判断一个类是另一个类的子类或者子孙类,语法:issubclass(sub,sup)
    • isinstance(obj, Class) 布尔函数如果obj是Class类的实例对象或者是一个Class子类的实例对象则返回true。

    方法重写

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

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    class Parent:        # 定义父类
       def myMethod(self):
          print '调用父类方法'
     
    class Child(Parent): # 定义子类
       def myMethod(self):
          print '调用子类方法'
     
    c = Child()          # 子类实例
    c.myMethod()         # 子类调用重写方法
    

      执行结果:

    调用子类方法
    

    基础重载方法

    下表列出了一些通用的功能,你可以在自己的类重写:

    运算符重载

    Python同样支持运算符重载,实例如下:

    #!/usr/bin/python
     
    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)
     
    v1 = Vector(2,10)
    v2 = Vector(5,-2)
    print v1 + v2
    

    执行结果:

    Vector (7,8)
    

    类属性与方法

      类的私有属性

          __private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs

      类的方法

          在类的内部,使用 def 关键字可以为类定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数

      类的私有方法

          __private_method两个下划线开头,声明该方法为私有方法,不能在类地外部调用。在类的内部调用 self.__private_methods

    class JustCounter:
        __secretCount = 0  #私有成员
        publicCount = 0    #公有成员
        def count(self):
            self.__secretCount += 1
            self.publicCount += 1
            print self.__secretCount
    
    counter = JustCounter()
    counter.count()
    counter.count()
    print counter.publicCount
    #print counter.__secretCount  #报错,私有成员,不能通过对象直接进行访问
    print counter._JustCounter__secretCount  #可以通过object._className__attrName 这样组合的方式进行访问私有成员
    

     执行结果:

    1
    2
    2
    2
    

    单下划线、双下划线、头尾双下划线说明:

    • __foo__: 定义的是特殊方法,一般是系统定义名字 ,类似 __init__() 之类的。

    • _foo: 以单下划线开头的表示的是 protected 类型的变量,即保护类型只能允许其本身与子类进行访问,不能用于 from module import *

    • __foo: 双下划线的表示的是私有类型(private)的变量, 只能是允许这个类本身进行访问了。

      

     

      

      

      

     

  • 相关阅读:
    阿里风控大脑关于大数据应用的探索与实践
    MaxCompute
    Lyft 基于 Flink 的大规模准实时数据分析平台(附FFA大会视频)
    基于MaxCompute InformationSchema进行血缘关系分析
    阿里经济体大数据平台的建设与思考
    厉害了!阿里云首批通过边缘云标准符合性测试
    边缘计算和“寒武纪”有什么关系?阿里云资深专家刘强如是说
    阿里云荣获最佳智能边缘计算技术创新平台
    阿里云杨敬宇:四层技术构建基于城市场景的边缘计算
    阿里云移动研发平台 EMAS 助力银行业打造测试中台,提升发版效能
  • 原文地址:https://www.cnblogs.com/yuanqiangfei/p/8117169.html
Copyright © 2011-2022 走看看