• python学习之【第十七篇】:Python中的面向对象(类和对象)


    1.什么是类和类的对象?

    类是一种数据结构,我们可以用它来定义对象,后者把数据值和行为特性融合在一起,类是现实世界的抽象的实体以编程形式出现。实例是这些对象的具体化。类是用来描述一类事物,类的对象指的是这一类事物的一个个体。例如:“人”就是一个类,而男人,女人,小孩等就是“人”这个类的实例对象;再比如“动物”也是一个类,而猫,狗等就是“动物”这个类的实例对象。

    1.1 类的构成

    在Python中,类(class)由3个部分构成:

    • 类的名称:类名;
    • 类的属性:一组数据;
    • 类的方法:进行操作的方法;

    1.2 类的声明和定义

    在Python中,类声明和函数声明很相似,头一行用class关键字,接下来是一个作为它的定义的代码体,如下所示:

    class 类名(object):
        '类的说明解释文档'
        类体
    

    注:通常,类名命名规则采用大驼峰式命名。

    1.3 类的对象

    在Python中,可以根据已经定义好的类去创建出一个个对象,创建对象也叫做实例化对象,对象是由类实例化而来的,类实例化的结果称为一个实例或者称为一个对象。

    实例化对象的语法是:

    对象名 = 类名()
    

    例如:现有一个“车”类,而BMW是“车”类的一个对象,实例化这个对象即就是:

    BMW = Car()
    

    2._init_() 构造函数

    __init__()方法是类的构造器,在实例化对象时,主要完成对对象的一些初始设定。当类被调用时,实例化的第一步就是创建实例对象,一旦对象创建了,Python就会检查在类里面是否实现了__init__()方法,如果没有定义__init__()方法,则实例化对象时会创建出一个没有任何属性的空对象。

    __init__()方法主要有以下特点:

    • __init__()方法,在实例化对象时会被自动调用,不需要手动调用;
    • __init__()方法中,第1个参数必须为self,如果在实例化对象时传递了2个实参,那么__init__()方法中除了self作为第一个形参外还需要2个形参,即__init__(self,x,y);
    • 在调用类实例化对象时,__init__()方法中的self参数,不需要开发者传递,Python解释器会自动把当前的对象引用传递进去;

    示例:

    class Car(object):
        """这是一个Car类"""
    
        # 数据属性
        def __init__(self, wheel, color):
            self.wheel = wheel
            self.color = color
    
        def get_car_info(self):
            print('车轮子个数%s,车的颜色%s' % (self.wheel, self.color))
    
        # 函数属性
        def move(self):
            print('车正在移动。。。')
    
    
    BMW = Car(4, '红色')
    BMW.move()
    BMW.get_car_info()
    print(BMW.wheel)
    print(BMW.color)
    """
    输出:
    车正在移动。。。
    车轮子个数4,车的颜色红色
    4
    红色
    """
    

    3.类属性

    定义在类里面的属性叫做类属性,类属性可以在各个实例之间共享,包括父类的类属性也可以在子类的实例中共享,类可以访问类属性,但不能访问实例属性。类属性分为:数据属性和函数属性。

    class Car(object):
        # 数据属性
        wheel_num = 4
        
        # 函数属性
        def move(self):
            print('车正在移动。。。')
    
    
    

    3.1 类属性的增

    向类里面增加新的类属性。

    语法:

    类名.新类属性名 = 新类属性值
    

    示例:

    class Car(object):
        # 数据属性
        wheel_num = 4
    
        # 函数属性
        def move(self):
            print('车正在移动。。。')
    
    
    print('增加之前', Car.__dict__)
    Car.color = 'black'
    print(Car.color)  # 输出 black
    print('增加之后', Car.__dict__)
    """
    输出:
    增加之前 {'__module__': '__main__', 'wheel_num': 4, 'move': <function Car.move at 0x00000000027C9950>, '__dict__': <attribute '__dict__' of 'Car' objects>, '__weakref__': <attribute '__weakref__' of 'Car' objects>, '__doc__': None}
    black
    增加之后 {'__module__': '__main__', 'wheel_num': 4, 'move': <function Car.move at 0x00000000027C9950>, '__dict__': <attribute '__dict__' of 'Car' objects>, '__weakref__': <attribute '__weakref__' of 'Car' objects>, '__doc__': None, 'color': 'black'}
    """
    

    3.2 类属性的删

    删除类里面的某一个类属性。

    语法:

    del 类名.类属性
    

    示例:

    class Car(object):
        # 数据属性
        wheel_num = 4
    
        # 函数属性
        def move(self):
            print('车正在移动。。。')
    
    
    print('删除之前', Car.__dict__)
    del Car.wheel_num
    print('删除之后', Car.__dict__)
    """
    输出:
    删除之前 {'__module__': '__main__', 'wheel_num': 4, 'move': <function Car.move at 0x0000000002799950>, '__dict__': <attribute '__dict__' of 'Car' objects>, '__weakref__': <attribute '__weakref__' of 'Car' objects>, '__doc__': None}
    删除之后 {'__module__': '__main__', 'move': <function Car.move at 0x0000000002799950>, '__dict__': <attribute '__dict__' of 'Car' objects>, '__weakref__': <attribute '__weakref__' of 'Car' objects>, '__doc__': None}
    """
    

    3.3 类属性的改

    修改类里面的某个类属性。

    语法:

    类对象.类属性 = 新值
    

    示例:

    class Car(object):
        # 数据属性
        wheel_num = 4
    
        # 函数属性
        def move(self):
            print('车正在移动。。。')
    
    
    print('修改之前', Car.wheel_num)  # 输出 修改之前 4
    Car.wheel_num = 5
    print('修改之后', Car.wheel_num)  # 输出 修改之后 5
    

    注意:

    如果修改类属性,必须通过 类对象.类属性 = 新值 去修改,不能通过实例访问类属性修改,如果使用实例访问类属性修改类属性,只会在实例中新建一个与类属性同名的实例属性,并且当实例属性与类属性同名时,实例只会访问到实例属性,而不会去访问类属性。

    3.4 类属性的查

    访问类属性直接使用类名.类属性即可访问。

    如果需要查看某个类中都有哪些类属性时,可以使用内置属性_dict_进行查看,该内置属性返回一个字典,包含了类中所有的属性。

    示例:

    class Car(object):
        # 数据属性
        wheel_num = 4
    
        # 函数属性
        def move(self):
            print('车正在移动。。。')
    
    
    print(Car.__dict__)
    """
    输出:
    {'__module__': '__main__', 
    'wheel_num': 4, 
    'move': <function Car.move at 0x00000000027F9950>,
    '__dict__': <attribute '__dict__' of 'Car' objects>, 
    '__weakref__': <attribute '__weakref__' of 'Car' objects>, 
    '__doc__': None}
    """
    

    3.5 类的几个特殊属性

    类里面除了有自定义的属性外,还有几个特殊的内置属性。

    • _name_:返回类的名字
    • _doc_:返回类的文档字符串
    • _base_:返回类的第一个父类
    • _bases_:返回类的所有父类构成的元组
    • _module_:返回类定义所在的模块
    • _class_:返回实例对应的类

    示例:

    class Car(object):
        """这是一个Car类"""
        # 数据属性
        wheel_num = 4
    
        # 函数属性
        def move(self):
            print('车正在移动。。。')
    
    
    print(Car.__name__)  # 输出 Car
    print(Car.__doc__)  # 输出 这是一个Car类
    print(Car.__base__)  # 输出 <class 'object'>
    print(Car.__bases__)  # 输出 (<class 'object'>,)
    print(Car.__module__)  # 输出 __main__
    print(Car.__class__)  # 输出 <class 'type'>
    

    4. 实例属性

    实例仅仅拥有数据属性,实例属性只是与某个类的实例相关联的数据值,并且可以通过点的方式进行访问,这些值独立于其他实例或类,当一个实例被释放后,它的属性同时也被清除了。

    设置实例属性可以在实例创建后的任意时间进行,但通常是在构造函数__init__()方法中进行设定,因为在实例化对象时,__init__()方法是最早执行的,__init__()方法执行完毕,即返回实例对象,实例对象也就拥有了设定好的实例属性。

    4.1 实例属性的增

    增加一个实例属性。

    语法:

    实例对象.新属性名 = 属性值
    

    示例:

    class Car(object):
        """这是一个Car类"""
    
        # 数据属性
        def __init__(self, wheel, color):
            self.wheel = wheel
            self.color = color
    
        def get_car_info(self):
            print('车轮子个数%s,车的颜色%s' % (self.wheel, self.color))
    
        # 函数属性
        def move(self):
            print('车正在移动。。。')
    
    
    BMW = Car(4, '红色')
    print('增加之前:', BMW.__dict__)
    BMW.brand = 'BMW X5'
    print('增加之后:', BMW.__dict__)
    """
    输出:
    增加之前: {'wheel': 4, 'color': '红色'}
    增加之后: {'wheel': 4, 'color': '红色', 'brand': 'BMW X5'}
    """
    

    4.2 实例属性的删

    删除一个实例属性。

    语法:

    del 实例对象.新属性名
    

    示例:

    class Car(object):
        """这是一个Car类"""
    
        # 数据属性
        def __init__(self, wheel, color):
            self.wheel = wheel
            self.color = color
    
        def get_car_info(self):
            print('车轮子个数%s,车的颜色%s' % (self.wheel, self.color))
    
        # 函数属性
        def move(self):
            print('车正在移动。。。')
    
    
    BMW = Car(4, '红色')
    print('删除之前:', BMW.__dict__)
    del BMW.color
    print('删除之后:', BMW.__dict__)
    """
    输出:
    删除之前: {'wheel': 4, 'color': '红色'}
    删除之后: {'wheel': 4}
    """
    

    4.3 实例属性的改

    修改一个实例属性。

    语法:

    实例对象.新属性名 = 新属性值
    

    示例:

    class Car(object):
        """这是一个Car类"""
    
        # 数据属性
        def __init__(self, wheel, color):
            self.wheel = wheel
            self.color = color
    
        def get_car_info(self):
            print('车轮子个数%s,车的颜色%s' % (self.wheel, self.color))
    
        # 函数属性
        def move(self):
            print('车正在移动。。。')
    
    
    BMW = Car(4, '红色')
    print('修改之前:', BMW.color)   # 输出 修改之前: 红色
    BMW.color = '黑色'
    print('修改之后:', BMW.color)   # 输出 修改之后: 黑色
    

    4.4 实例属性的查

    查看实例属性直接使用实例对象.实例属性即可。

    5.实例方法、类方法、静态方法

    5.1 实例方法

    实例方法就是正常在类里面定义的方法,不需要任何装饰器装饰,并且第一个参数必须是实例对象self

    注:实例方法只能通过实例对象访问。

    class Car(object):
        """这是一个Car类"""
    
        def __init__(self, wheel, color):
            self.wheel = wheel
            self.color = color
    
        # 实例方法
        def get_car_info(self):
            print('车轮子个数%s,车的颜色%s' % (self.wheel, self.color))
    
    
    BMW = Car(4, '红色')
    BMW.get_car_info()    # 通过实例对象访问实例方法
    

    5.2 类方法

    类方法就是类所拥有的方法,需要用装饰器@classmethod来标识,对于类方法,第一个参数必须是类对象cls

    注:类方法可以通过类对象和实例对象访问。

    class Car(object):
        """这是一个Car类"""
    
        def __init__(self, wheel, color):
            self.wheel = wheel
            self.color = color
    
        # 类方法
        @classmethod
        def run(cls):
            print('车子都会跑。。。')
    
    
    BMW = Car(4, '红色')
    BMW.run()   # 通过实例对象访问类方法
    Car.run()   # 通过类对象访问类方法
    

    5.3 静态方法

    静态方法通常定义一些与实例和类都没有关系的方法。静态方法需要通过装饰器@staticmethod来标识,静态方法没有必须得参数,根据方法参数可有可无。

    注:类方法可以通过类对象和实例对象访问。

    class Car(object):
        """这是一个Car类"""
    
        def __init__(self, wheel, color):
            self.wheel = wheel
            self.color = color
    
        # 静态方法
        @staticmethod
        def brand():
            print('这是一辆宝马车。')
    
    
    BMW = Car(4, '红色')
    BMW.brand()   # 通过实例对象访问静态方法
    Car.brand()   # 通过类对象访问静态方法
    

    (完)

  • 相关阅读:
    Mysql 源码安装
    mysql的主从复制
    Centos7通过glib方式安装mysql
    Host is not allowed to connect to this MySQL server解决方法
    MobaXterm记录日志
    Linux的录屏
    ShardingJdbc垂直分库及公共表
    应用系统间几种数据传输方式
    关于加班
    对函数式编程的简单理解
  • 原文地址:https://www.cnblogs.com/wangjiachen666/p/9802887.html
Copyright © 2020-2023  润新知