美文网首页
面向对象知识点总结

面向对象知识点总结

作者: 那是个好男孩 | 来源:发表于2019-07-07 16:28 被阅读0次
目录
import time

def init_str_del():
    class Teacher(object):
        # 类属性:在方法外、类内部定义的属性
        # 对象没创建的时候就想使用一个属性 那么就可以定义一个类属性
        country = "中国"

        # 隐匿的添加对象属性
        # 实例属性:在init方法内定义的属性
        def __init__(self,name,age):
            self.name = name
            self.age = age

        # 输出对象的时候,不想看到对象的内存地址,那么魔法方法__str__可以返回对象的描述信息
        def __str__(self):
            # 返回一个字符串信息
            return '我叫:%s 年龄:%d' % (self.name, self.age)

        # 1.程序退出,程序中所使用到的对象全部销毁
        # 2.当前对象的内存地址没有变量使用的时候,那么对象销毁
        def __del__(self):
            print('对象被释放了:', self)

        def show_info(self):
            print("python3里的旧式类自动继承object")
            print(self.name, self.age)

    teacher = Teacher('邓川', 21)
    teacher.show_info()

    '''################### 类属性的操作 ###################'''
    # 访问类属性
    print(Teacher.country)
    # 使用类不能访问对象属性
    # print(Teacher.age)

    # 修改类属性
    Teacher.country = '中国0'
    print(Teacher.country)
    # 查看类属性和方法
    print(Teacher.__dict__)

    '''################### 实例属性的操作 ###################'''
    print(teacher.name)
    # 对象可以访问类属性
    print(teacher.country)

    # 对象不能修改类属性,其实是添加了一个对象属性
    print("-" * 20)
    print(Teacher.__dict__)
    print(teacher.__dict__)
    teacher.country = '中国人1'
    print(teacher.country)
    print(Teacher.__dict__)
    print(teacher.__dict__)

    # 其实记住一个原则就好,类属性由类去操作,实例属性由对象去操作就不会出错!!!
    # 对象可以访问类属性 不能修改

    print(teacher.__dict__)
    # 使用实例修改对象属性
    teacher.name = '李四'
    print(teacher.name)
    print(teacher.__dict__)

    '''################### 静态动态添加属性 ###################'''

    # 没有init方法的时候,可以动态的添加对象属性
    teacher.name = '李四'
    teacher.age = 18
    teacher.show_info()
    # 可以修改属性
    teacher.name = '王五'
    print(teacher.name, teacher.age)

    # 查看Teacher类继承的父类
    print(Teacher.__bases__)

    '''################### __str__方法 ###################'''

    # 输出对象 自动调用__str__方法
    print(teacher)

    '''################### __del__方法 ###################'''
    # 删除变量     => 对象先释放再退出 (第2种)
    del teacher
    # => 程序退出了对象再被释放(第1种)
    # teacher0 = teacher
    # del teacher

    # 引用计数:内存地址被变量使用的次数,当引用计数为0 表示对象被销毁
    time.sleep(3)
    print('程序退出了')


def single_inherit():
    class Animal(object):
        # 对象方法
        def run(self):
            print("动物跑起来了")

    class Dog(Animal):
        # 重写:子类继承父类,父类的方法满足不了子类的需要可以对父类的方法进行重写
        # 重写的特点:1.继承关系 2.方法名相同
        def run(self):
            print("小狗跑起来了")

        def wang(self):
            # 在此调用父类的方法
            # <1>self,前提:当前类里面没有父类的方法,否则调用的是当前类里面的方法,因为重写了
            self.run()
            # <2>使用父类的类名 如果使用类名调用对象方法需要传入实例对象
            Animal.run(self)

            # <3>super调用父类的方法
            # 根据指定类,在类继承链中获取下一个类
            # 提示:1.Dog表示根据指定类找类继承链中获取下一个类
            #      2.self表示获取self对象类型的类继承链
            #      3.super不一定是你直接继承的父类!!!单继承直接理解成是继承的父类没有问题,但是多继承就有可能不是
            #      4.super调用的是父类的方法,但是不一定是你直接继承父类的方法
            super(Dog, self).run()
            print(self.__class__.mro())
            

            print('汪')

    # 在python里面的方法调用会遵循mro,类继承顺序,也就是在某个类里找到了就不会再找了
    # print(Dog.mro())
    dog = Dog()

    dog.wang()
    dog.run()


def more_inherit():
    class A(object):
        def show_a(self):
            print('我是A类')

    class B(object):
        def show_b(self):
            print('我是B类')

    class C(A,B):
        def show(self):
            # 查看类的继承顺序
            print(self.__class__.mro())
            # 指定类A要在self对象类继承顺序中找下一个类
            super(A,self).show_b()
            print('我是C类')
            # super(C,self).show_b()也是可以的!!!因为有继承关系!输出结果是一样的
    C().show()


def init_inherit():
    class A():
        def __init__(self,name):
            print("A")
            self.name = name


    class B(A):
        # 提示:如果子类提供了调用的方法,那么不会主动调用父类的方法
        def __init__(self, subject):
            # 调用父类的__init__方法
            # self.__init__('DC') 这种写法错误 因为方法名一样 在这会递归

            # 使用类名调用父类的init方法
            A.__init__(self, '李四')

            # super调用父类里面的init
            super(B,self).__init__('王五')

            # 简写 super() -> super(B,self)
            super().__init__('小明')


            print("B")
            self.subject = subject

        def show(self):
            print("我是B类")

    b = B("PYTHON")
    print(b.subject)
    print(b.name)
    b.show()


def rewrite_super():
    class Person(object):
        def show(self):
            print('我是人类')

    class Plane(object):
        def show(self):
            print('飞机')

        def fly(self):
            print('飞机可以飞')

    class Student(Person,Plane):
        def show(self):
            print(self.__class__.mro())
            # 方法重写也可以使用super,调用父类的方法
            super(Person,self).show()

    dc = Student()
    dc.show()


def private_attributes_method():
    # 在属性名和方法名加上 两个下划线 '__' 那么定义的属性和方法就是私有属性和私有方法
    class Person(object):
        def __init__(self,name,age):
            self.name = name
            # 私有属性,只能在本类内部使用,在类外面不能使用
            # 注意点:私有属性只能在init方法里面添加
            self.__age = age
            
        def show(self):
            # 在类内部使用私有属性和私有方法是可以的
            print(self.name, self.__age)
            self.__money()

        def __money(self):
            print("100万")

    person = Person('DC', 20)
    print(person.name)
    # 私有属性在外界访问不了
    # print(person.__age)
    person.show()
    # 私有方法在外界访问不了
    # person.__money()

    # 查看对象中的属性信息
    print(person.__dict__)
    # 本意是修改私有属性
    # 在这里不是修改了私有属性,而是给对象添加了一个__age的对象属性
    # 提示:这里也不是添加的私有属性,只能在init方法里面添加
    person.__age = 22
    print(person.__age)
    print(person.__dict__)
    # 查看类属性和方法
    print(Person.__dict__)

    # 在python里面私有属性和私有方法没有做到绝对的私有,只是进行了一个名字的伪装
    # 非常规操作 不建议这样使用
    print(person.__dict__)
    print(person._Person__age)
    person._Person__age = 34
    print(person.__dict__)
    print(person._Person__age)

    person._Person__money()
    person.show()


def inherit_private():
    class Person(object):
        def __init__(self):
            self.__age = 18

    def __show(self):
        print('我是一个私有方法')

    class Student(Person):
        # def show(self):
        #     print(student.__age)
        #     student.__show()
        pass

    student = Student()
    # print(student.__age)
    # student.__show()
    # student.show()
    # 总结:子类继承父类,不能直接使用父类的私有属性和私有方法


def classMethod_staticMethod():
    class Person(object):
        # 私有类属性
        __mytype = '黄种人'

    def __init__(self):
        self.name = 'zww'
    # 定义对象方法:在方法的参数里面有self表示对象方法
    def show(self):
        print('我是人类')

    # 定义类方法 cls表示当前类
    @classmethod
    def show_info(cls):
        print(cls)
        print('我是一个类方法')

    # 定义静态方法 提示:静态方法和当前对象和当前类没有关系,不会使用self和cls
    @staticmethod
    def show_msg():
        print('我是一个静态方法')

    # 应用场景:用类方法可以修改类属性
    @classmethod
    def set_type(cls, mytype):
        cls.__mytype = mytype

    # 返回一个类的私有属性
    @classmethod
    def get_type(cls):
        return cls.__mytype

    # ----------------------------------对象方法是最通用的方法,可以修改对象属性和类属性
    def instance_set_type(self, mytype,name):
        # self.__mytype = mytype 不要这样写,这样写就添加了一个对象属性
        # self.__class__ 获取对象所对应的类
        self.__class__.__mytype = mytype

        print(self.name)
        # 修改对象属性
        self.name = name

    # 获取对应的类属性
    def instance_get_type(self):
        print(self.name)
        return self.__class__.__mytype

    # ---------------------------------------------------既不需要当前对象也不需要当前类
    @staticmethod
    def sum_num(num1, num2):
        return num1 + num2

    p = Person()
    p.show()
    p.show_info()
    p.show_msg()

    p.set_type('白种人')
    result = p.get_type()
    print(result)

    p.instance_set_type('黑种人','DC')
    print(p.instance_get_type())
        
    print(p.sum_num(1, 2))

    # 类调用静态方法和类方法不需要传入当前类,如果类调用对象方法需要传入一个实例
    Person.show_msg()
    # Person.show(p) # 一般都不这样干
    Person.show_info()  


def polymorphism():
    # 多态: 关注的是同一个方法,但是会出现不同的表现形式,在python里不需要关注类型
    class Text(object):
        def show(self):
            print('显示文字')

    class Image(object):
        def show(self):
            print('显示图片')

    class Video(object):
        def show(self):
            print('显示视频')

    class Person(object):
        def show(self):
            print('我在跳舞')

    # 实现显示数据的功能
    def show_data(data):
        # 关心的是 同一个 方法,会出现不同的表现形式,那么这种操作叫做多态
        # 在python里面多态:只关心对象的方法,不关心对象的类型
        data.show()

    image = Image()
    video = Video()
    p = Person()
    show_data(p)


def new():
    # 单例:在应用程序中不管创建多少次对象只有一个实例对象 内存地址是一样的
    class Person(object):
        
        # 私有的类属性
        __instance = None

        # 创建对象
        def __new__(cls, *args, **kwargs):
            # if cls.__instance == None:
            if not cls.__instance:
                print("创建对象")
                # 把创建的对象给类属性
                cls.__instance = object.__new__(cls)
            
            return cls.__instance
        
        def __init__(self,name,age):
            print('初始化')
            self.name = name
            self.age = age

    p1 = Person('张三', 20)
    # p1对象已经创建了,在这里返回已经创建的对象的内存地址,然后对P2对象进行初始化
    # p1、p2的内存地址是一样的 p2初始化的内容覆盖了p1初始化的内容
    p2 = Person('李四', 22)
    print(p1, p2)
    print(p1.name, p2.name)  # 李四 李四


def slots():
    # 指明创建对象的时候不能再添加其它属性,只能是指定的属性
    class Student(object):
        # 这样的操作可以让对象的属性固定
        __slots__ = ('name', 'age')

        def __init__(self,name,age):
            self.name = name
            self.age = age

    stu = Student('xx', 20)
    print(stu.name,stu.age)

    stu.name = '李四'
    stu.age = 21
    # stu.sex = '女'

    print(stu.name,stu.age)


def method_to_variable():
    '''
    class Student(object):
        
        def __init__(self):
            self.__score = 100

        def set_score(self, score):
            self.__score = score

        def get_score(self):
            return self.__score

    stu = Student()
    score = stu.get_score()
    print(score)

    stu.set_score(99)
    score = stu.get_score()
    print(score)
    '''
    class Student(object):
        
        def __init__(self):
            self.__score = 100
            
        # 把方法改成对应的属性
        # 获取值
        @property
        def get_score(self):
            return self.__score

        # 设置值
        @get_score.setter
        def set_score(self, score):
            self.__score = score

    stu = Student()
    score = stu.get_score
    print(score)

    stu.set_score = 80
    score = stu.get_score
    print(score)



if __name__ == '__main__':
    # variable静态动态的添加 魔法方法str和del
    init_str_del()

    # 单继承 使用类名调用父类的方法
    single_inherit()
    
    # 多继承 super的使用
    more_inherit()

    # __init__方法中使用super
    init_inherit()

    # 在重写方法中使用super
    rewrite_super()

    # 私有属性和私有方法
    private_attributes_method()

    # 子类不能直接使用父类的私有属性和私有方法
    inherit_private()

    # 类方法和静态方法
    classMethod_staticMethod()

    # 多态
    polymorphism()

    # 单例
    new()

    # 指明创建对象的时候不能再添加其它属性,只能是指定的属性
    slots()

    # 把方法改成对应的属性
    method_to_variable()

相关文章

网友评论

      本文标题:面向对象知识点总结

      本文链接:https://www.haomeiwen.com/subject/fazbhctx.html