python-16-元类和异常

115 阅读1分钟

元类

class Feng:
    def __init__(self):
        print('init')
f = Feng()
print(type(f))
print(type(Feng))

def __init__(self,name,age):
    self.name = name
    self.age = age
def test(self):
    print('test')

Feng_new = type('Feng_new',(object,),{'x':2,'__init__':__init__,'test':test})
print(Feng_new)
print(Feng_new.__dict__)
#{'x': 2, '__init__': <function __init__ at 0x00000000004D2EA0>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Feng_new' objects>, '__weakref__': <attribute '__weakref__' of 'Feng_new' objects>, '__doc__': None}
fs = Feng_new('fengfeng',18)
print(fs.__dict__)
fs.test()

异常

#异常处理
try:
    age = input('>:')
    int(age)
except ValueError as e:
    print(e)

#通用异常
try:
    age = input('>:')
    int(age)
except Exception as e:
    print(e)
finally:
    print('go to it')

#断言
def test():
    ref = 1
    return ref
res1 = test()
# assert res1 == 2
#等同于
if res1 !=2:
    raise AssertionError('....')