Python面向对象

慕课网上《Python-面向对象》课程个人总结笔记,侵删。
慕课网视频链接:https://www.imooc.com/learn/747

一、课程介绍

1.1 Python面向对象课程介绍

复用性、灵活性、扩展性

二、面向对象概念

2.1 Python面向对象概念

面向对象是一种抽象

两个基本概念:类、对象

基本要素:属性、方法

三、Python面向对象

3.1 用Python定义类

构造函数:__init__

析构函数:__del__

内建函数:dir(属性)、type(类型)

3.2 Python面向对象-定义类的属性

对象定义:直接在类里定义、在构造函数里定义

访问控制:没有访问控制、没提供私有属性控制

编程规范约束:(不是python语法约束)

class Programer(object):
    def __init__(self, name, age, weight):
        self.name = name          # 公有属性
        self._age = age           # 私有属性
        self.__weight = weight    # 私有属性,语法限制
        #  后者可以通过_Programer__weight访问

3.3 Python面向对象-定义类的方法

函数:直接调用函数名调用

方法:必须与对象结合起来使用,可看作method属性

方法的访问控制:

class Example(object):
    def add(self):              # 公有属性
        pass
    def _minus(self):           # 私有属性
        pass
    def __multiply(self):       # 私有属性,语法限制
        pass

装饰器@classmethod(类似属性中的直接调用方法):用类名调用,而不是,某个对象

装饰器@property(类似属性中的访问属性调用方法):像访问属性一样调用方法

class Programer(object):
    hobby = 'play computer'
    def __init__(self, name, age, weight):
        self.name = name
        self._age = age
        self.__weight = weight
        
    @classmethod
    def get_hobby(cls):
        return cls.hobby
        
    @property
    def get_weight(self):
        return self.__weight
        
    def self_introduction(self):
        print ('My name id %s \nI am %s years old \n' % (self.name, self._age))

if __name__ == '__main__':
    programer = Programer('Albert',25,80)
    print (Programer.get_hobby())     # 直接用类名调用
    print (programer.get_weight)      # 不加括号调用
    programer.self_introduction()

3.4 Python面向对象-类的继承

定义类:class son(father)

子类:会继承父类的属性和方法,也可以自己定义来覆盖父类的属性和方法

super()调用父类的方法:

class A(object):
    def method(self, arg):
        pass
class B(A):
    def method(self, arg):
        super(B, self).method(arg)

用类名调用父类的方法:(不建议)

class A(object):
    def method(self, arg):
        pass
        
class B(A):
    def method(self, arg):
       A.method(arg)

子类的类型判断:isinstance(判断类型)、issubclass(判断是否是子类)

class Programer(object):
    hobby = 'play computer'
    
    def __init__(self, name, age, weight):
        self.name = name
        self._age = age
        self.__weight = weight
        
    @classmethod
    def get_hobby(cls):
        return cls.hobby
        
    @property
    def get_weight(self):
        return self.__weight
        
    def self_introduction(self):
        print ('My name id %s \nI am %s years old \n' % (self.name, self._age))

class BackendProgramer(Programer):
    def __init__(self, name, age, weight, language):
        super(BackendProgramer,self).__init__(name,age,weight)
        self.language = language

if __name__ == '__main__':
    programer = BackendProgramer('Albert',25,80,'Python')
    print (dir(programer))
    print (programer.__init__)
    print (type(programer))
    print (isinstance(programer,Programer))

3.5 Python面向对象-类的多态

多态的要素:继承、方法重写

class Programer(object):
    hobby = 'play computer'
    
    def __init__(self, name, age, weight):
        self.name = name
        self._age = age
        self.__weight = weight
        
    @classmethod
    def get_hobby(cls):
        return cls.hobby
        
    @property
    def get_weight(self):
        return self.__weight
        
    def self_introduction(self):
        print ('My name id %s \nI am %s years old \n' % (self.name, self._age))

class BackendProgramer(Programer):
    def __init__(self, name, age, weight, language):
        super(BackendProgramer,self).__init__(name,age,weight)
        self.language = language
        
    def self_introduction(self):
        print ('My name id %s \nMy favorote language %s \n' % (self.name, self.language))

def introduce(programer):
    if isinstance(programer, Programer):
        programer.self_introduction()

if __name__ == '__main__':
    programer = Programer('Albert',25,80)    
    backend_programer = BackendProgramer('Tim',30,70,'Python')
    introduce(programer)
    introduce(backend_programer)

四、深入Python面向对象

4.1 Python面向对象-magic method简介

包含:方法名的前后有俩个下划线

4.2 Python面向对象-对象的实例化

创建类的对象:__new__(cls)

初始化对象:__init__(self)

回收对象:__del__() # 由python回收机制调用,不可控

class Programer(object):
    def __new__(cls, *args, **kwargs):
        print ('call __new__ method')
        print (args)
        return super(Programer,cls).__new__(cls)

    def __init__(self, name, age):
        print ('call __init__ method')
        self.name = name
        self.age = age

if __name__ == '__main__':
    programer = Programer('Albert',25)
    print (programer.__dict__)

4.3 Python面向对象-类与运算符

比较运算符:

__cmp__(self, other)
__eq__(self, other)
__lt__(self, other)
__gt__(self, other)

数字运算符:

__add__(self, other)
__sub__(self, other)
__mul__(self, other)
__div__(self, other)

逻辑运算符:

__or__(self, other)
__and__(self, other)

代码示例:

class Programer(object):
    def __init__(self, name, age):
        self.name = name
        if isinstance(age,int):
            self.age = age
        else:
            raise Exception('age must be int')

    def __eq__(self, other):
        if isinstance(other, Programer):
            if self.age == other.age:
                return True
            else:
                return False  
        else:
             raise Exception('The type of object must be Programer')

    def __add__(self, other):
        if isinstance(other, Programer):
            return self.age + other.age 
        else:
             raise Exception('The type of object must be Programer')

if __name__ == '__main__':
    p1 = Programer('Albert', 25)
    p2 = Programer('Bill', 30)
    print (p1 == p2)
    print (p1 + p2)

4.4 Python面向对象-类的展现

转换成字符串:

__str__       # 适合人看
__repr__      # 适合机器看
__unicode__

展现对象属性:

__dir__

示例代码:

class Programer(object):
    def __init__(self, name, age):
        self.name = name
        if isinstance(age,int):
            self.age = age
        else:
            raise Exception('age must be int')

    def __str__(self):
        return '%s is %s years old' % (self.name, self.age)

    def __dir__(self):
        return self.__dict__.keys()

if __name__ == '__main__':
    p = Programer('Albert', 25)
    print (p)
    print (dir(p))

4.5 Python面向对象-类的属性控制

设置对象属性:

__setattr__(self, name, value)

使用示例:

def __setattr__(self, name, value):      #错误,无限递归
    setattr(self, name, value)

def __setattr__(self, name, value):      #正确
    self.__dict__[name] = value

查询对象属性:

__getattr__(self, name)           # 默认属性没有被查询到的情况下调用
__getattribute__(self, name)      # 每次访问属性都会被调用到(容易引起无限递归)

删除对象属性:

__delattr__(self, name)

代码示例:

class Programer(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def __getattribute__(self, name):
        # return getattr(self, name)
        # return self.__dict__[name]
        return super(Programer, self).__getattribute__(name)

    def __setattr__(self, name, value):
        # setattr(self, name, value)
        self.__dict__[name] = value


if __name__ == '__main__':
    p = Programer('Albert', 25)
    print (p.name)

五、课程总结

5.1 Python面向对象-课程总结

还有更多,建议去官方文档看Magic Method。

你可能感兴趣的:(Python学习初涉)