首页 > 编程语言 > 详细

Python面向对象(结束)

时间:2019-10-01 23:34:04      阅读:114      评论:0      收藏:0      [点我收藏+]

面向对象

一、特殊修饰符

  共有成员:

  私有成员:__.成员名(私有化:在成员名前加两个下划线)

    实际是封装为 _类名__成员名

    -外部无法直接访问

    -子类也无法直接访问父类的私有成员 1 class F:

 2     def __init__(self):
 3         self.ge=123
 4         self.__gene=123
 5         
 6 classs S(F):
 7     def __init__(self,name):
 8         self.name=name
 9         self.__age=18
10         super(S,self).__init__()
11     def show(self):
12         print(self.name)
13         print(self.__age)
14         print(self.ge)
15         print(self.__gene)
16 
17 s=S(zhangsan)
18 s.show()

二、特殊成员

  __init__:obj=类名(),创建该类对象,且默认执行__init__()方法;

  __del__:析构方法,与构造方法相反,对象被销毁时调用;

   __call__:对象名+() 默认执行的方法;

1 class Foo:
2     def  __init__(self):
3         print(init)
4 
5     def  __call__(delf,*args,**kwargs):
6          print(call)
7 
8 Foo()()

  __int__:int(对象),自动执行__int__()方法。

  __str__:str(对象),自动执行__str__()方法。

 1 class  Foo:
 2     def  __init__(self):
 3         pass
 4 
 5     def  __int__(self):
 6         return 1111
 7 
 8     def  __str__(self):
 9         return  asdf
10 
11 obj=Foo()
12 print(obj,int(obj),str(obj))

  __dict__:将对象中封装的所有内容通过字典形式返回;

技术分享图片

三、metaclass,类的祖宗

  a、Python中一切事物都是对象

  b、class  Foo:

      pass

    obj=Foo()

    obj是Foo的实例对象;Foo是type的类对象

1 class  Foo(object):
2     def  func(self):
3         print(123)
4 相当于==================
5 def  function(self):
6     print(123)
7 
8 Foo = type(Foo,(object,),{func:function})
9 声明一个类对象;类对象名:Foo,继承于(object),类对象中有一方法叫func
 1 class  MyType(type):
 2     def  __init__(self,*args,**kwargs):
 3         #self=Foo
 4         print(MyType    init)
 5         super(Mytype,self).__init(what,bases,dict)
 6 
 7     def  __call__(self,*args,**kwargs):
 8         #self=Foo
 9         print(MyType    call)
10         obj=self.__new__(selt,*args,**kwargs)
11         self.__init__(obj)
12 
13 class  Foo(object,metaclass=MyType):
14     def  __init__(self)
15         print(Foo    init)
16 
17     def  __new__(cls,*args,**kwargs):
18         #cls=Foo
19         print(Foo   __new__)
20         return  object.__new__(cls,*args,**kwargs)
21 
22 coj=Foo()
23 
24 输出结果:
25         MyType    init
26         MyType    call
27         Foo   __new__
28         Foo    init
29 
30 第一阶段:解释器从上到下执行代码创建Foo类,先调用MyType中的__init__();
31 第二阶段:通过Foo类创建obj对象;
32     1、Foo是MyType的对象,所以Foo()首先调用MyType中的__call__();
33     2、通过Foo类创建obj对象:依次调用
34             MyType的__call__():对象+()自动调用的方法
35             Foo的__new__():创建Foo的对象
36             Foo的__init__():实例化Foo对象

  c、类对象都是type的对象   type(...);实例对象都是类对象的对象

Python面向对象(结束)

原文:https://www.cnblogs.com/TianLiang-2000/p/11616312.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!