1. 程式人生 > >反射和類內置方法

反射和類內置方法

bject style ssm 信息 put pre @class turn ttr

# class Teacher:
#     dic = {‘查看學生信息‘: ‘show_student‘, ‘查看老師‘: ‘show_teacher‘}
#
#     def show_student(self):
#         print(‘show student‘)
#
#     def show_teacher(self):
#         print(‘show teacher‘)
#
#     @classmethod
#     def func(cls):
#         print(‘func‘)
#
# chen = Teacher()
# key = input(‘input:‘)
# if hasattr(chen, Teacher.dic[key]): # func = getattr(chen, Teacher.dic[key]) # print(func) # class A: # name = ‘1‘ # # def func(self): # print(‘aaaaaa‘) # # a = A() # if hasattr(a, ‘name‘): # ret1 = getattr(a, ‘name‘) # ret2 = getattr(a, ‘func‘) # print(ret1) #
ret2() class A: pass def __str__(self): return >>str def __repr__(self): return repr # %s print()和str(obj)都是調用__str__ # repr(obj)和%r都是調用__repr__ # 如果本類無__str__, 就實現__repr__, repr是str的備胎,但str不能做repr的備胎 a = A() print(a) # 打印對象就是調用__str__方法,如果本類無實現str方法,會調用object的__str__(內存地址)
print(%s %a) print(str(a)) print(repr(a)) print(%r%a) # class A: # def __init__(self, name): # self.name = name # # def __call__(self): # print(self.__dict__) # # a = A(‘chen‘)()

反射和類內置方法