反射和类内置方法
Posted hhsh
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了反射和类内置方法相关的知识,希望对你有一定的参考价值。
# 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‘)()
以上是关于反射和类内置方法的主要内容,如果未能解决你的问题,请参考以下文章