美文网首页
python面向对象2

python面向对象2

作者: Dxes | 来源:发表于2019-11-26 19:55 被阅读0次
    1.权限访问:
    公开的(public):类的里面、类的外面都可以使用,也可以被继承
    保护的(protect):类的里面可以使用,类的外面不能使用,可以被继承
    私有的(private):类的里面可以使用,类的外面不能使用,也不能被继承
    
    2.python中类的内容的访问权限

    严格来说,python类中的内容只有公开的;私有化是假的私有化

    3.怎么私有化

    在方法名前或者属性名前加(但是名字后面不加)
    原理:不是真的私有化,而是在_开头的属性和方法名前加了‘类名’

    class Preson:
          num = 61
          __num2 = 100
          def __init__(self,name,age = 18):
                self.name = name
                self.age = age
                self.gender = "男"
                self.gender = "男"
    
          def func1(self):
                print('%s今年%d岁' % (self.name,self.age),self.__gender)
                self.func11()
    
          def __func11(self):
                print('私有的对象方法')
          
          @staticmethod
          def func2():
                print("我是静态方法1")
          
          @staticmethod
           def __func22():
                print("我是静态方法1")
    
          @classmethod
           def  func3(cls):
                  print(cls.num)
                  print(cls.__num2)
    print("=============默认公开的属性和方法在类的外面都可以用=========")
    print(Person.num)
    
    p1 = Person('小明')
    print(p1.name,p1.age,p1.gender)
    
    p1.func1()
    
    Person.func2()
    print("============私有的属性和方法=============")
    # print(Person.__num2)    # AttributeError: type object 'Person' has no attribute '__num2'
    Person.func3()
    # print(p1.__gender)  # AttributeError: 'Person' object has no attribute '__gender'
    # p1.__func11()   # AttributeError: 'Person' object has no attribute '__func11'
    # Person.__func22()   # AttributeError: type object 'Person' has no attribute '__func22'
    
    print(p1.__dict__)   # 可以看到名字
    print(p1._Person__gender)
    print(Person._Person__num2)
    
    

    1.getter和setter

    1)什么时候使用
    如果希望在对象属性赋值前做点儿别的什么事情就会给这个属性添加setter
    如果希望在获取属性值之前做点儿别的什么事情就给这个属性添加getter

    2)怎么用
    getter:
    a.将需要添加getter的属性名前加_
    b.声明函数:声明前加@property;
    函数名就是不带_的属性名;
    函数需要一个返回值,返回值就是获取这个属性能够得到的值
    c.在外面使用属性的时候不带下划线

    setter:
    注意:如果想要给属性添加setter必须先添加getter
    a.声明函数:声明前加@getter名.setter;
    函数名就是不带_的属性名;
    函数不需要返回值,但是需要一个参数,这个参数就是给属性赋的值
    b.在外面给属性赋值的时候不带下划线

    class Person:
            def __init__(self,age:int):
                 self.age = age
                 self._time = 0
            
            @ property
            def time(self):
                  t_time = time.localtime(self._time)
                  return '{}-{}-{} {}:{}:{}',format(t_tiame.tm_year,t_time.tm_mon,t_time.tm_mday,t_time.tm_hour,t_time.tm_min,t_time.tm_sec)
        
            @property
              def age(self):
                    return  self._age
    
    
            @ age.setter
              def age(self,value):
                      print("value:",value)
                      if isinstance(value,int):
                              if 0<= value <= 200:
                                  self._age = value
                              else:
                                  raise ValueError
                      else:
                              raise ValueError
    p1 = Person(10)
    p1.age = 18
    # p1.age = 'abc'
    # p1.age = [1, 2, 3]
    # p1.age = 19273897298
    
    print(p1.time)
    
    class Circle:
            pi = 3.1415926
    
            def __init__(self,r):
                  self.r = r
                  self._area = 0
    
           @property
           def area(self):
                  return Circle.pi * self.f * self.r
    
            @area.setter
            def area(self,value):
                  print(给area属性赋值:',value)
                  raise ValueError
    
    c1 = Circle(1)
    
    print(c1.area)  # 本质是在调用area函数:c1.area()
    
    c1.r = 10
    print(c1.area)  # 本质是在调用area函数:c1.area()
    
    c1.r = 3
    print(c1.area)  # 本质是在调用getter的area函数:c1.area()
    
    # c1.area = 31.4   # 本质是在调用setter的area函数: c1.area(31.4)
    # c1.area = 1000   # 本质是在调用setter的area函数: c1.area(1000)
    
    

    1.什么是继承

    继承是让子类直接拥有父类的属性和方法
    子类 - 继承者(儿子)
    父类 - 被继承者(爸爸),又叫超类

    2.怎么继承

    语法:
    class 类名(父类1,父类2,……):
    类的说明文档
    类的内容

    3.继承那些东西

    父类所有的属性和方法都会继承

    class Person(object):
             num = 61
             
             def __inti__(self):
                   self.name = '小明'
                   self.age = 18
    
             @staticmethod
              def func1():
                     print("静态方法")
    
    
    class Student(Preson):
              pass
    
    # 子类直接使用父类的属性和方法
    print(Student.num)
    Student.func1()
    
    stu = Student()
    print(stu.name,stu.age)
    
    4.子类中添加属性和方法

    1)添加字段和方法
    在子类中直接声明新的字段和方法;
    注意:如果添加的字段名和方法名和父类的字段方法同名了,子类中的字段和方法会覆盖父类的字段和方法 ->重写

    2)添加对象属性
    在自己的init方法中添加新的属性,并且需要通过super()去调用父类init方法继承父类的对象属性

    5.super的应用

    可以在类中任何一个方法或者类方法中通过super()调用父类的对象想方法或者类方法

    super(类1,类1的对象).方法() --> 调用类1的父类中的方法
    super().方法 等价于 super(当前类,当前类的对象)

    super(type,obj) -> 要求obj必须是type的对象或者是type的子类对象

    class Animal:
        num = 100
    
        def __init__(self):
            self.age = 10
            self.gender = '雌'
    
        @staticmethod
        def a_func1():
            print('动物的对象方法1')
    
        @staticmethod
        def func1():
            print('动物中的静态方法')
    
        def func2(self):
            print('动物中的对象方法2')
    
        @classmethod
        def func4(cls):
            print('动物中的类方法')
    
    
    class Cat(Animal):
        voice = '喵~'
    
        def __init__(self):
            super().__init__()    # 调用当前类的父类的__init__方法
            self.color = '白色'
            self.breed = '加菲猫'
    
    
        @classmethod
        def c_func1(cls):
            print('猫的类方法')
    
        @staticmethod
        def func1():
            print('猫中的静态方法')
            # 注意: 静态方法中不能直接使用super()
            # super().a_func1()
    
        def func3(self):
            super().func2()
            print('猫中的对象方法')
    
        @classmethod
        def func5(cls):
            print('猫中的类方法2')
            super().func4()
    
    
    print(Cat.num, Cat.voice)
    Cat.a_func1()
    Cat.c_func1()
    Cat.func1()   # 猫中的静态方法
    Animal.func1()  # 动物中的静态方法
    
    cat1 = Cat()
    print(cat1.age, cat1.gender)
    print(cat1.color, cat1.breed)
    
    print('===============super================')
    cat1.func3()
    Cat.func5()
    
    class A:
        def func(self):
            print('this is A')
    
    
    class B(A):
        def func(self):
            print('this is B')
    
    
    class D(A):
        def func(self):
            print('this is D')
    
    class C(B):
        def func(self):
            # super().func()
            # super(C, self).func()
            # super(B, self).func()
            # super(D, D()).func()
            # super(A, A()).func()
            print('this is C')
    
    obj = C()
    
    # ==> super().func()
    # obj.func()  # this is B; this is C
    
    # ==> super(C, self).func()
    # obj.func()   #  this is B;  this is C
    
    # ==> super(B, B()).func()  /  super(B, self).func()
    # obj.func()    # this is A;  this is C
    
    # ==> super(D, D()).func()
    # obj.func()    # this is A;  this is C
    
    # ==> super(A, A()).func()
    # obj.func()    # AttributeError: 'super' object has no attribute 'func'
    

    多继承
    class Animal:
        num = 100
    
        def __init__(self, age=0, gender='雄'):
            self.age = age
            self.gender = gender
    
        def a_func1(self):
            print('动物的对象方法')
    
        def message(self):
            print('this is Animal')
    
    
    class Fly:
        flag = '飞行'
    
        def __init__(self, height=1000, time=3):
            self.height = height
            self.time = time
    
        @classmethod
        def f_func1(cls):
            print('飞行的类方法')
    
        def message(self):
            print('this is Fly')
    
    
    class Bird(Animal, Fly):
        pass
    
    
    class A1:
        def message(self):
            super(Bird, Bird()).message()
    
    
    b1 = Bird()
    
    # 字段都可以继承
    print(Bird.num, Bird.flag)
    
    # 方法都可以继承
    b1.a_func1()
    Bird.f_func1()
    
    # 对象属性只能继承第一个父类的
    print(b1.age, b1.gender)
    # print(b1.height, b1.time)   # AttributeError: 'Bird' object has no attribute 'height'
    
    b1.message()
    
    A1().message()
    
    

    class A:
        def message(self):
            print('this is A')
    
    
    class B:
        def message(self):
            print('this is B')
    
    
    class C(A, B):
        def message(self):
            super().message()
            print('this is C')
    
    
    # this is A
    # this is C
    C().message()
    
    print('=================================================')
    # 查看继承顺序: 先画出和需要的类相关联的所有的父类的继承关系,然后从左往右看没有子类的类
    
    class A:
        def message(self):
            print('this is A')
    
    
    class B(A):
        def message(self):
            super().message()
            print('this is B')
    
    
    class C(A):
        def message(self):
            super().message()
            print('this is C')
    
    
    class D(B, C):
        def message(self):
            super().message()
            print('this is D')
    
    class E(C):
        def message(self):
            super().message()
            print('this is E')
    
    class F(D, E):
        def message(self):
            super().message()
            print('this is F')
    
    class G(F):
        def message(self):
            super().message()
            print('this is G')
    
    D().message()
    """
    'this is A'
    'this is B'
    'this is D'
    """
    print(D.__mro__)
    print('=========================================')
    F().message()
    
    print('==================================================')
    class A:
        def message(self):
            print('this is A')
    
    class B:
        def message(self):
            super().message()
            print('this is B')
    
    
    class C(B, A):
        def message(self):
            super().message()
            print('this is C')
    
    class D(B):
        def message(self):
            super().message()
            print('this is D')
    
    class E(C):
        def message(self):
            super().message()
            print('this is E')
    
    class F(D, E):
        def message(self):
            super().message()
            print('this is F')
    
    
    class K(F):
        def message(self):
            super().message()
            print('this is K')
    
    
    F().message()
    print(F.__mro__)
    

    相关文章

      网友评论

          本文标题:python面向对象2

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