反射和一些内置方法

#反射
#what?   反射:使用字符串数据类型的变量名来获取这个变量的值
#why?  为什么要用反射:三大场景
        #input
        #文件
        #网络

#反射类中的变量 getattr(变量名:命名空间,字符串:属于一个命名空间内的变量名)
#反射  静态属性,类方法和静态方法
# class Foo:
#   School = 'oldboy'
#   Country = 'China'
#   language = 'Chinese'
# inp = input('>>:')
# print(getattr(Foo,inp))

class Foo:
  School = 'oldboy'
  Country = 'China'
  language = 'Chinese'
  @classmethod
  def class_method(cls):
    print(cls.School)
  @staticmethod
  def static_method():
    print(Foo.School)

  def wahaha(self):
    print('wahaha')
getattr(Foo,'static_method')()
getattr(Foo,'wahaha')(1)
#反射对象中的变量


#反射模块的变量


#反射本文件中的变量
import sys
a = 1
b = 2
name = 'alex'
def qqxing():
  print('qqxing')
print(sys.modules['__main__'])#本文件的命名空间
print(getattr(sys.modules['__main__'],'a'))
getattr(sys.modules[__name__],'qqxing')()
print(sys.modules[__name__])#反射本文件中的变量

  








在不是需要程序员定义,本身就存在在类中的方法就是内置方法 内置的方法通常都长这样 : __名字__ 名字 : 双下方法、 魔术方法、 内置方法 __init__ 不需要我们主动调用,而是在实例化的时候内部自动调用的 所有的双下方法,都不需要我们直接去调用,都有另外一种自动触发它的语法 __str__ __repr__ class Course: def __init__(self,name,period,price,teacher): self.name= name self.period = period self.price = price self.teacher = teacher def __str__(self): return 'str : %s %s %s %s' % (self.name, self.period, self.price, self.teacher) def __repr__(self): return 'repr : %s %s %s %s' % (self.name, self.period, self.price, self.teacher) course_lst = [] python = Course('python','6 month',29800,'boss jin') course_lst.append(python) linux = Course('linux','5 month',25800,'oldboy') course_lst.append(linux) for id,course in enumerate(course_lst,1): # print('%s %s %s %s %s'%(id,course.name,course.period,course.price,course.teacher)) print(id,course) print('%s %s'%(id,course)) print(str(course)) print(repr(course)) print('%r'%course) __str__ 当你打印一个对象的时候 触发__str__ 当你使用%s格式化的时候 触发__str__ str强转数据类型的时候 触发__str__ __repr__ repr是str的备胎 有__str__的时候执行__str__,没有实现__str__的时候,执行__repr__ repr(obj)内置函数对应的结果是 __repr__的返回值 当你使用%r格式化的时候 触发__repr__ 学生选择课程的时候,要显示所有的课程 class Foo: # def __str__(self): # return 'Foo.str' def __repr__(self): return 'Foo.repr' class Son(Foo): pass # def __str__(self): # return 'Son.str' # def __repr__(self): # return 'Son.repr' s1 = Son() print(s1)

  

猜你喜欢

转载自www.cnblogs.com/xxy614899502/p/9567952.html