zoukankan      html  css  js  c++  java
  • Python面向对象

    Python面向对象

    现实世界中,随处可见的一种事物就是对象,对象是事物存在的实体,如人类、汽车、动物、水果这些都是一个抽象的类别,我们所见到的实物都是这些类的具体存在,因此类是对象的抽象集合,对象是类的具体表现。现实世界是万物皆对象!


     一、基本特征

    • 类(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例
    • 类变量:类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用
    • 数据成员:类变量或者实例变量用于处理类及其实例对象的相关的数据
    • 方法重写:如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写
    • 实例变量:定义在方法中的变量,只作用于当前实例的类
    • 继承:即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。例如,有这样一个设计:一个Dog类型的对象派生自Animal类,这是模拟"是一个(is-a)"关系(例图,Dog是一个Animal)
    • 实例化:创建一个类的实例,类的具体对象
    • 方法:类中定义的函数
    • 对象:通过类定义的数据结构实例。对象包括两个数据成员(类变量和实例变量)和方法

     二、创建类

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

    实例:

    class Student():
        '所有学生的基类'
        count=0
        def __init__(self,name,city):
            self.name=name
            self.city=city
            Student.count+=1
            print("My name is %s and come from %s" %(name,city))
    
        def talk(self):
            print("Hello everyone!")
    
        def displaycount(self):
            print("The total count is %d" %Student.count)
    • count 变量是一个类变量,它的值将在这个类的所有实例之间共享。你可以在内部类或外部类使用 Student.count 访问
    • 第一种方法__init__()方法是一种特殊的方法,被称为类的构造函数或初始化方法,当创建了这个类的实例时就会调用该方法
    • self 代表类的实例,self 在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数

    self代表类的实例,而非类

    类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称, 按照惯例它的名称是 self

    class Test():
        def prt(self):
            print(self)
            print(self.__class__)
    
    t=Test()
    t.prt()

    运行结果:

    <__main__.Test object at 0x00000000010C3CC0>
    <class '__main__.Test'>

    从执行结果可以很明显的看出,self 代表的是类的实例,代表当前对象的地址,而 self.class 则指向类。

    self 不是 python 关键字,我们把他换成 world 也是可以正常执行的:

    class Test():
        def prt(world):
            print(world)
            print(world.__class__)
    
    t=Test()
    t.prt()

    运行结果:

    <__main__.Test object at 0x00000000010C3D68>
    <class '__main__.Test'>


    三、创建实例对象

    实例化类其他编程语言中一般用关键字 new,但是在 Python 中并没有这个关键字,类的实例化类似函数调用方式。

    以下使用类的名称 Employee 来实例化,并通过 __init__ 方法接受参数

    stu1=Student('nancy','Chengdu')
    stu2=Student('anne','Chongqing')

     四、访问属性

    您可以使用点(.)来访问对象的属性。使用如下类的名称访问类变量

    stu1=Student('nancy','Chengdu')
    stu2=Student('anne','Chongqing')
    print("The count is ",Student.count)

    运行结果:

    My name is nancy and come from Chengdu
    My name is anne and come from Chongqing
    The count is 2

    你可以添加,删除,修改类的属性,如下所示:

    Student.age=23
    Student.age=25
    del Student.age

     五、Python内置类属性

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

    实例如下:

    print('__dict__:',Student.__dict__)   # 类的属性(包含一个字典,由类的数据属性组成)
    print('__doc__:',Student.__doc__)     # 类的文档字符串
    print('__name__:',Student.__name__)   # 类名
    print('__module__:',Student.__module__)  # 类定义所在模块
    print('__base__:',Student.__base__)   # 类的所有父类构成元素

    运行结果:

    __dict__: {'__module__': '__main__', 'talk': <function Student.talk at 0x00000000010ACE18>, '__dict__': <attribute '__dict__' of 'Student' objects>, '__init__': <function Student.__init__ at 0x00000000010ACD90>, '__weakref__': <attribute '__weakref__' of 'Student' objects>, 'count': 2, '__doc__': '所有学生的基类', 'displaycount': <function Student.displaycount at 0x00000000010ACEA0>}
    __doc__: 所有学生的基类
    __name__: Student
    __module__: __main__
    __base__: <class 'object'>


     六、Python对象销毁(垃圾回收)

    Python 使用了引用计数这一简单技术来跟踪和回收垃圾。

    在 Python 内部记录着所有使用中的对象各有多少引用。

    一个内部跟踪变量,称为一个引用计数器。

    当对象被创建时, 就创建了一个引用计数, 当这个对象不再需要时, 也就是说, 这个对象的引用计数变为0 时, 它被垃圾回收。但是回收不是"立即"的, 由解释器在适当的时机,将垃圾对象占用的内存空间回收。

    实例:

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

    class Point():
        def prt(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))
    del pt1
    del pt2
    del pt3

    运行结果:

    7290496 7290496 7290496
    Point 销毁


     七、类的继承

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

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

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

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

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

    实例:

    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)
    
    class child(Parent):
        def __init__(self):
            print('调用子类构造函数')
        def childMethod(self):
            print('调用子类方法')
    
    c=child()
    c.childMethod()
    c.ParentMethod()
    c.setAttr(333)
    c.getAttr()

    运行结果:

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


     八、方法重写

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

    实例:

    class parent():
        def myMethod(self):
            print('调用父类方法')
    
    class child():
        def myMethod(self):
            print('调用子类方法')
    
    c=child()
    c.myMethod()

    运行结果:

    调用子类方法


     九、运算符重载

    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(3,4)
    v2=Vector(5,-2)
    print(v1+v2)

    运行结果:

    Vector (8,2)


     十、类属性与方法

    1、类的私有属性

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

    2、类的方法

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

    3、类的私有方法

    __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)    # 报错,实例不能访问私有变量

    运行结果:

    1

    2

    2

    Traceback (most recent call last):

    File "test.py", line 17, in <module>

    print counter.__secretCount

     AttributeError: JustCounter instance has no attribute '__secretCount'

    Python不允许实例化的类访问私有数据,但你可以使用 object._className__attrName 访问属性,将如下代码替换以上代码的最后一行代码:

    print(counter._Justcounter__secretCount)

    运行结果:

    1
    2
    2
    2

     参考教程:http://www.runoob.com/python/python-object.html

  • 相关阅读:
    [Angular] Using the platform agnostic Renderer & ElementRef
    [HTML5] Focus management using CSS, HTML, and JavaScript
    [TypeScript] Increase TypeScript's type safety with noImplicitAny
    [React] displayName for stateless component
    [Redux] Important things in Redux
    [HTML5] Using the tabindex attribute for keyboard accessibility
    [Angular] @ViewChild and template #refs to get Element Ref
    [Angular] @ViewChildren and QueryLists (ngAfterViewInit)
    [Angular] Difference between Providers and ViewProviders
    [Angular] Difference between ngAfterViewInit and ngAfterContentInit
  • 原文地址:https://www.cnblogs.com/NancyRM/p/8033593.html
Copyright © 2011-2022 走看看