python面向对象2

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__)
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,430评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,406评论 3 398
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,834评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,543评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,547评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,196评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,776评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,671评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,221评论 1 320
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,303评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,444评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,134评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,810评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,285评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,399评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,837评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,455评论 2 359

推荐阅读更多精彩内容