面向对象——内置方法

  • isinstance(obj,cls)检查obj是否是类 cls 的对象
  • issubclass(sub, super)检查sub类是否是 super 类的派生类
  •  1 # isinstance()#检查obj是否是类 cls 的对象
     2 class Foo(object):
     3     pass
     4 obj = Foo()
     5 print(isinstance(obj,Foo))#True
     6 # issubclass()
     7 class Foo(object):#检查sub类是否是 super 类的派生类
     8     pass
     9 class Bar(Foo):
    10     pass
    11 print(issubclass(Bar, Foo))#True
    View Code
  • item系列,把obj模拟成字典去操作它的属性 
  • __getitem__,__setitem__,__delitem__
  •  1 #item系列,把obj模拟成字典去操作它的属性
     2 class Foo:
     3     def __init__(self,name):
     4         self.name = name
     5     def __getitem__(self, item):
     6         # print('getitem...')
     7         return self.__dict__.get(item)
     8     def __setitem__(self, key, value):
     9         # print('setitem...')
    10         self.__dict__[key] = value
    11     def __delitem__(self, key):
    12         # print('delitem...')
    13         # self.__dict__.pop(key)
    14         del self.__dict__[key]
    15 obj = Foo('egon')
    16 #查看属性
    17 #以前是obj.属性名
    18 # obj['name']#  等价于obj.name
    19 # print(obj['name'])#egon
    20 # print(obj.name)#egon
    21 
    22 #设置属性:
    23 # obj.sex = 'male'
    24 # obj['sex'] = 'male'
    25 # print(obj.__dict__)
    26 # print(obj.sex)
    27 
    28 #删除属性
    29 #del obj.name
    30 # del obj['name']
    31 # print(obj.__dict__)
    View Code
  • __str__:定制对象的字符串形式
  •  1 class People:
     2     def __init__(self,name,age):
     3         self.name = name
     4         self.age = age
     5     def __str__(self):
     6         # print('====>str')
     7         return '<name:%s,age:%s>'%(self.name,self.age)
     8 obj = People('egon',18)
     9 print(obj)#obj.__str__()
    10 #<name:egon,age:18>
    View Code
  • __del__:析构方法,当对象在内存中被释放时,自动触发执行
  •  1 class Open:
     2     def __init__(self,filename):
     3         print('open file.....')
     4         self.filename = filename
     5     def __del__(self):
     6         del self.filename
     7         print('回收操作系统资源:self.close()')
     8 f = Open('settings.py')
     9 # del f  #手动,不调用的话是在程序结束后自动调用
    10 print('----main----')
    11 print(f.filename)
    12 """
    13 open file.....
    14 ----main----
    15 settings.py
    16 回收操作系统资源:self.close()
    17 """
    View Code
  •  1 class Open:
     2     def __init__(self,filename):
     3         print('open file.....')
     4         self.filename = filename
     5     def __del__(self):
     6         del self.filename
     7         print('回收操作系统资源:self.close()')
     8 f = Open('settings.py')
     9 del f  #手动,不调用的话是在程序结束后自动调用
    10 print('----main----')
    11 # print(f.filename)  #报错
    12 """
    13 open file.....
    14 回收操作系统资源:self.close()
    15 ----main----
    16 """
    View Code
原文地址:https://www.cnblogs.com/GraceZ/p/8087454.html