Python基础(18)_面向对象程序设计2(反射、__str__、__del__、__item__系列)

一 isinstance(obj,cls)和issubclass(sub,super)

isinstance(obj,cls)检查是否obj是否是类 cls 的对象

class Foo(object):
    pass
 obj = Foo()

print(isinstance(obj, Foo))

issubclass(sub, super)检查sub类是否是 super 类的派生类

class Foo(object):
    pass
 
class Bar(Foo):
    pass
 
print(issubclass(Bar, Foo))
>>True

二、反射

python面向对象中的反射:通过字符串的形式操作对象相关的属性。python中的一切事物都是对象(都可以使用反射)

四个实现反射的函数:

hasattr(object,name:判断object中有没有一个name字符串对应的方法或属性

getattr(object, name, default=None):获取属性

setattr(x, 'y', v) :设置属性,is equivalent to ``x.y = v''

delattr(x, 'y') :删除属性,is equivalent to ``del x.y''

四个方法使用的演示:

class BlackMedium:
    feature='Ugly'
    def __init__(self,name,addr):
        self.name=name
        self.addr=addr

    def sell_house(self):
        print('%s 黑中介卖房子啦,傻逼才买呢,但是谁能证明自己不傻逼' %self.name)
    def rent_house(self):
        print('%s 黑中介租房子啦,傻逼才租呢' %self.name)

b1=BlackMedium('万成置地','回龙观天露园')

#检测是否含有某属性
print(hasattr(b1,'name'))
print(hasattr(b1,'sell_house'))

#获取属性
n=getattr(b1,'name')
print(n)
func=getattr(b1,'rent_house')
func()

# getattr(b1,'aaaaaaaa') #报错
print(getattr(b1,'aaaaaaaa','不存在啊'))

#设置属性
setattr(b1,'sb',True)
setattr(b1,'show_name',lambda self:self.name+'sb')
print(b1.__dict__)
print(b1.show_name(b1))

#删除属性
delattr(b1,'addr')
delattr(b1,'show_name')
delattr(b1,'show_name111')#不存在,则报错

print(b1.__dict__)

四个方法的使用演示  

  

三、__str__

__str__:定义在类内部的内置的绑定方法,打印的会自动将对象传入

class Teacher:
    def __init__(self,name,age):
        self.name=name
        self.age=age
        self.courses=[]

    def teach(self):
        print('%s teach' %self.name)

    def __str__(self):
        return '<name:%s age:%s>' %(self.name,self.age)

class Course:
    def __init__(self,name,price,period):
        self.name=name
        self.price=price
        self.period=period
    def __str__(self):
        return '《name:%s price:%s period:%s》' %(self.name,self.price,self.period)

egon=Teacher('egon',18)
print(egon) #egon.__str__()
>>:
<name:egon age:18>


python=Course('python',20000,'6mon')
openstack=Course('openstack',10,'3mon')
linux=Course('linux',1,'1mon')

egon.courses.append(python)
egon.courses.append(openstack)
egon.courses.append(linux)

# egon.courses.extend([python,openstack,linux])
print(egon.courses)
for obj in egon.courses:
  print(obj)


>>: [<__main__.Course object at 0x0000027F4FF70748>, <__main__.Course object at 0x0000027F4FF70780>, <__main__.Course object at 0x0000027F4FF70710>] 《name:python price:20000 period:6mon》 《name:openstack price:10 period:3mon》 《name:linux price:1 period:1mon》

四、__del__

析构方法,当对象在内存中被释放时,自动触发执行。

import time
class Foo:
    def __init__(self,x):
        self.x=x
        print('connect mysql') #conn=abcdef('192.168.1.10',3306)

    def __del__(self):
        '''做一些与这个对象有关的清理操作'''
        # conn.close()
        # file.close()
        print('====>')


f=Foo(10)
del f   #f.__del__()
time.sleep(3)
print('主程序')
>>:
connect mysql
====>
主程序


f=Foo(10)
time.sleep(3)
print('主程序')
>>:
connect mysql
主程序
====>

 

五、__item__系列

 

class Foo:
    def __init__(self,name,age,sex):
        self.name=name
        self.age=age
        self.sex=sex
    def __getitem__(self, item):
        # print(self,item,type(item))
        # return getattr(self,item)
        return self.__dict__[item]
    def __setitem__(self, key, value):
        # setattr(self,key,value)
        self.__dict__[key]=value

    def __delitem__(self, key):
        # delattr(self,key)
        self.__dict__.pop(key)

    def __len__(self):
        return 10
f=Foo('egon',18,'male')
print(f.name) #f['name']
print(f.age) #f['age']
print(f.sex) #f['sex']

print(f['name'])

f['name']='egon_nb'
print(f.__dict__)
del f['name']
print(f.__dict__)
print(len(f))


>>: egon 18 male egon {'name': 'egon_nb', 'age': 18, 'sex': 'male'} {'age': 18, 'sex': 'male'} 10
原文地址:https://www.cnblogs.com/hedeyong/p/7132642.html