zoukankan      html  css  js  c++  java
  • Python面向对象(成员修饰符)

    day25

    成员修饰符

     1 class Foo:
     2     def __init__(self, name, age):
     3         self.name = name
     4         self.__age = age#私有,外部无法直接访问
     5 
     6     def show(self):
     7         return self.__age
     8 obj = Foo('alex', 19)
     9 print(obj.name)
    10 
    11 #print(obj.__age)
    12 
    13 ret = obj.show()
    14 print(ret)#间接访问

    __age为私有成员,不能直接访问。

    执行结果:

    alex
    19
    
    Process finished with exit code 0

    私有方法

     1 class Foo:
     2     def __f1(self):
     3         return 123
     4 
     5     def f2(self):
     6         r = self.__f1()
     7         return r
     8 obj = Foo()
     9 ret = obj.f2()#间接访问
    10 print(ret)

    私有方法间接访问。

    执行结果:

    123
    
    Process finished with exit code 0

    私有成员不被继承

     1 class F:
     2     def __init__(self):
     3         self.ge = 123
     4         self.__gene = 123
     5 
     6 class S(F):
     7     def __init__(self,name):
     8         self.name = name
     9         self.__age = 18
    10         super(S, self).__init__()
    11 
    12     def show(self):
    13         print(self.name)#alex
    14         print(self.__age)#18
    15         print(self.ge)#父类中的公有成员
    16         #print(self.__gene)#父类中的私有成员,不能被继承
    17 
    18 s = S('alex')
    19 s.show()

    第16行,父类中的私有成员,不能被继承。

    执行结果:

    alex
    18
    123
    
    Process finished with exit code 0
  • 相关阅读:
    miniNExT
    使用ExaBGP发送BGP路由信息和清洗DDoS流量
    HTML day02(html列表与菜单的制作)
    HTML day01基础总结
    SSH项目整合基本步骤
    常见异常类有哪些?
    JSP 生命周期
    HTTP状态码
    使用oracle删除表中重复记录
    Oracle三种分页?
  • 原文地址:https://www.cnblogs.com/112358nizhipeng/p/9829668.html
Copyright © 2011-2022 走看看