Day8 面向对象反射 item方法 打印对象信息__str__ 构析方法__del__ 程序的异常处理

反射:通过字符串来访问到所对应的值(反射到真实的属性上)。

eg:

 1 class Foo:
 2     x=1
 3     def __init__(self,name):
 4         self.name=name
 5 
 6     def f1(self):
 7         print('from f1')
 8 
 9 
10 # print(Foo.x) #Foo.__dict__['x']
11 
12 f=Foo('egon')
13 # print(f.__dict__)
14 #
15 # #1:
16 # print(f.name)
17 
18 #2:
19 # print(f.__dict__['name'])
20 
21 #hasattr
22 #反射到字典所对应的值
23 # print(hasattr(f,'name')) #f.name
24 # print(hasattr(f,'f1')) #f.f1
25 # print(hasattr(f,'x')) #f.x
26 
27 
28 #setattr   
29 #设置某个属性
30 # setattr(f,'age',18)#f.age=18
31 
32 #getattr
33 #得到某个属性的值
34 # print(getattr(f,'name'))#f.name
35 # print(getattr(f,'abc',None))#f.abc
36 # print(getattr(f,'name',None))#f.abc
37 
38 # func=getattr(f,'f1')#f.f1
39 # print(func)
40 # func()
41 #
42 
43 #delattr
44 #删除某个属性的值
45 # delattr(f,'name')# del f.name
46 # print(f.__dict__)

定义某个功能,输入某条命令,打印下面的功能:

class Ftpserver:
    def __init__(self,host,port):
        self.host=host
        self.port=port

    def run(self):
        while True:
            cmd=input('>>: ').strip()
            if not cmd:continue
            if hasattr(self,cmd):
                func=getattr(self,cmd)
                func()
    def get(self):
        print('get func')

    def put(self):
        print('put func')

item系列:

当触发某些属性的时候,执行某些操作。

 1 class Foo:
 2     def __getitem__(self, item):
 3         print('=====>get')
 4         return self.__dict__[item]    #执行你想要的操作
 5 
 6     def __setitem__(self, key, value):
 7         self.__dict__[key]=value
 8         # setattr(self,key,value)      #执行你想要的操作
 9 
10     def __delitem__(self, key):
11         self.__dict__.pop(key)         执行你想要的操作
12 
13 
14 f=Foo()
15 # f.x=1
16 # print(f.x)
17 # print(f.__dict__)
18 
19 f['x']=123123123123
20 
21 # del f['x']
22 
23 print(f['x'])

__str__:打印对象信息

在对象被打印的时候触发执行,只能返回字符串类型。

class People:
    def __init__(self,name,age,sex):
        self.name=name
        self.age=age
        self.sex=sex

    def __str__(self): #在对象被打印时触发执行
        return '<name:%s age:%s sex:%s>' %(self.name,self.age,self.sex)

p1=People('egon',18,'male')
p2=People('alex',38,'male')


print(p1)
print(p2)

__del__:在对象资源被释放的时候时触发。

eg:

 1 class Foo:
 2     def __init__(self,x):
 3         self.x=x
 4 
 5     def __del__(self): #在对象资源被释放时触发
 6         print('-----del------') 8 
 9 f=Foo(100000)
10 print('=======================>')

这种相当于在函数执行完了,

触发__del__这个方法

以后打印一个('-----del------')

如果在程序的执行过程中加入  del  (删除某个值得操作)

也会触发程序的执行

class Foo:
    def __init__(self,x):
        self.x=x

    def __del__(self): #在对象资源被释放时触发
        print('-----del------')
        print(self)

f=Foo(100000)
del f
print('=======================>')


程序异常的处理:

异常就是程序中运行是发生错误,错误的类型主要有这么几种:

1,语法错误(必须在程序运行之前解决)

2,逻辑错误

3,数据类型错误

4,索引错误

5,字典的key错误

如果错误发生的条件是不可预知的,则需要用到try....expect:在错误发生之后进行处理

基本语法为:

try:

  被检测的代码块

expect 异常类型:

  try中一旦检测到异常,就执行这个位置的逻辑

try:
    aaaa
    print('==-==>1')
    # l=[]
    # l[3]
    # print('==-==>2')
    # d={}
    # d['x']
    # print('==-==>3')
except NameError as e:
    print(e)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except Exception as e:
    print(e)
else:
    print('在没有错误的时候执行')
finally:
    print('无论有无错误,都会执行')


#raise   ......    在执行到某段的时候,自己抛出异常

#什么时候用try.....expect

是错误一定会发生,但是不确定在什么时候预知的条件时,用这个条件

原文地址:https://www.cnblogs.com/sexiaoshuai/p/7419775.html