# 反射
# 3w 1h
# what 是什么
    # 反射 使用字符串数据类型的变量名来获取这个变量的值
# a = 1
# b = 2
# name = 'alex'

# why 为什么 三个场景
    # input
        # 用户输入的如果是a,那么就打印1,如果输入的是b就打印2,如果输入的是name,就打印alex
    # 文件
        # 从文件中读出的字符串,想转换成变量的名字
    # 网络
        # 将网络传输的字符串转换成变量的名字
# where 在哪儿用
# how 怎么用

# 反射 ******
# hasattr *****
# getattr ******

# 反射类中的变量 : 静态属性,类方法,静态方法
# class Foo:
#     School = 'oldboy'
#     Country = 'China'
#     language = 'Chiness'
#
#     @classmethod
#     def class_method(cls):
#         print(cls.School)
#     @staticmethod
#     def static_method():
#         print('in staticmethod')
#
#     def wahaha(self):
#         print('wahaha')
# print(Foo.School)
# print(Foo.Country)
# print(Foo.language)
# 判断实现
# if inp == 'School':print(Foo.School)
# elif inp == 'Country':print(Foo.Country)
# elif inp == 'language':print(Foo.language)

# 反射实现
# while True:
#     inp = input('>>>')
#     print(getattr(Foo,inp))

# 解析getattr方法
# getattr(变量名:命名空间,字符串:属于一个命名空间内的变量名)
# getattr(Foo,'School')  # Foo.School
# print(Foo.class_method)
# print(getattr(Foo,'class_method'))
# getattr(Foo,'class_method')()    # Foo.class_method()
# getattr(Foo,'static_method')()   # Foo.static_method()
# getattr(Foo,'wahaha')(1)  # Foo.wahaha(1)
# print(hasattr(Foo,'wahaha'))
# print(hasattr(Foo,'shuangwaiwai'))

# 反射实现
# while True:
#     inp = input('>>>')
#     if hasattr(Foo,inp):
#         print(getattr(Foo,inp))

# 反射对象中的变量
# 对象属性
# 普通方法
# class Foo:
#     def __init__(self,name,age):
#         self.name = name
#         self.age = age
#
#     def eating(self):
#         print('%s is eating'%self.name)
# alex = Foo('alex_sb',83)
# print(getattr(alex,'name'))
# print(getattr(alex,'age'))
# getattr(alex,'eating')()

# 反射模块中的变量
import os # os就是一个模块
# os.rename('D:\骑士计划PYTHON1期\day21\__init__.py','D:\骑士计划PYTHON1期\day21\__init__.py.bak')
# getattr(os,'rename')('D:\骑士计划PYTHON1期\day21\__init__.py.bak','D:\骑士计划PYTHON1期\day21\__init__.py')

# 反射本文件中的变量  分析过程
# a = 1
# b = 2
# name = 'alex'
# def qqxing():
#     print('qqxing')

# cls.xxx
# obj.xxx
# os.xxx

# import sys
# print(sys.modules['__main__'])  # 本文件的命名空间
# print(sys.modules['__main__'].a)
# print([__name__]) # 变量,内置的变量

# 反射本文件中的变量  结论
# a = 1
# b = 2
# name = 'alex'
# def qqxing():
#     print('qqxing')
# class Foo:pass
#
# import sys
# print(sys.modules[__name__])     # 反射本文件中的变量 固定的使用这个命名空间
# print(getattr(sys.modules[__name__],'a'))
# print(getattr(sys.modules[__name__],'b'))
# print(getattr(sys.modules[__name__],'name'))
# getattr(sys.modules[__name__],'qqxing')()
# print(getattr(sys.modules[__name__],'Foo'))
# obj = getattr(sys.modules[__name__],'Foo')()
# print(obj)

# setattr
# delattr
# class Foo:
#     Country = 'China'
#
# def func():
#     print('qqxing')
#Foo.School = 'OLDBOY'
# setattr(Foo,'School','OLDOBY')  # 接受三个参数 命名空间 ‘变量名’ 变量值
# print(Foo.__dict__)
# print(getattr(Foo,'School'))
# print(Foo.School)

# setattr(Foo,'func',func)  # 一般没人往空间中添加函数
# print(Foo.__dict__)
# print(Foo.func)

# delattr
# del Foo.Country
# print(Foo.__dict__)
# delattr(Foo,'Country')
# print(Foo.__dict__)

# hasattr
# getattr
# setattr
# delattr

# 反射类中的变量
# 反射对象中的变量
# 反射模块中的变量
# 反射本文件中的变量

# 用反射的场景
# input
# 网络
# 文件
View Code

 



# 作业
# 选课 - 登录自动识别身份
# 场景 角色 类 —> 属性和方法
# 站在每个角色的角度上去思考程序执行的流程
import sys
class Course:
    def __init__(self,name,price,period,teacher):
        self.name = name
        self.price = price
        self.period = period
        self.teacher = teacher

class Student:
    operate_lst = [
                   ('查看所有课程', 'show_courses'),
                   ('选择课程', 'select_course'),
                   ('查看已选课程', 'check_selected_course'),
                   ('退出', 'exit')]
    def __init__(self,name):
        self.name = name
        self.courses = []

    def show_courses(self):
        print('查看可选课程')

    def select_course(self):
        print('选择课程')

    def check_selected_course(self):
        print('查看已选课程')

    def exit(self):
        exit()

class Manager:
    operate_lst = [('创建课程','create_course'),
                   ('创建学生','create_student'),
                   ('查看所有课程','show_courses'),
                   ('查看所有学生','show_students'),
                   ('查看所有学生的选课情况','show_student_course'),
                   ('退出','exit')]
    def __init__(self,name):
        self.name = name

    def create_course(self):
        print('创建课程')

    def create_student(self):
        print('创建学生')

    def show_courses(self):
        print('查看所有课程')

    def show_students(self):
        print('查看所有学生')

    def show_student_course(self):
        print('查看所有学生的选课情况')

    def exit(self):
        exit()

# 学生 : 登录就可以选课了
    # 有学生账号了
    # 有课程了

# 管理员 :登录就可以完成以下功能
    # 学生的账号是管理员创建的
    # 课程也应该是管理员创建的

# 应该先站在管理员的角度上来开发
# 登录
# 登录必须能够自动识别身份
# 用户名|密码|身份
def login():
    name = input('username : ')
    pawd = input('password : ')
    with open('userinfo', encoding='utf-8') as f:
        for line in f:
            usr,pwd,identify = line.strip().split('|')
            if usr == name and pawd == pwd:
                return {'result':True,'name':name,'id':identify}
        else:
            return {'result':False,'name':name}

ret = login()
if ret['result']:
    print('登录成功')
    if hasattr(sys.modules[__name__],ret['id']):
        cls = getattr(sys.modules[__name__],ret['id'])
        obj = cls(ret['name'])
        for id,item in enumerate(cls.operate_lst,1):
            print(id,item[0])
        func_str = cls.operate_lst[int(input('>>>')) - 1][1]
        print(func_str)
        if hasattr(obj,func_str):
            getattr(obj,func_str)()
else:
    print('登录失败')

    # if ret['id'] == 'Manager':
    #     obj = Manager(ret['name'])
    #     for id,item in enumerate(Manager.operate_lst,1):
    #         print(id,item[0])
    #     func_str = Manager.operate_lst[int(input('>>>')) - 1][1]
    #     if hasattr(obj,func_str):
    #         getattr(obj,func_str)()
    # elif ret['id'] == 'Student':
    #     obj = Student(ret['name'])
    #     for id,item in enumerate(Student.operate_lst,1):
    #         print(id,item[0])
    #     func_str = Student.operate_lst[int(input('>>>')) - 1][1]
    #     if hasattr(obj,func_str):
    #         getattr(obj,func_str)()
选课系统登录,类创建
boss_jin|666|Manager
zhuge|999|Student
text

 



# 内置方法
# __str__
# __repr__
# 在不是需要程序员定义,本身就存在在类中的方法就是内置方法
# 内置的方法通常都长这样 : __名字__
# 名字 : 双下方法、 魔术方法、 内置方法

# __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)
View Code

21天a卷函数提。 


内置函数:

 

enumerate()是python的内置函数,用于将一个可遍历的数据对象(如列表,元组或者字符串等)组合为一个索引序列,同事列出数据和数据下标,多用于for循环。

语法:

enumerate(a,start)

a是可迭代对象,start是计数起始数字

示例:

li = ['a','b','c','d','e','f']
for i in enumerate(li):
    print(i)
'''
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')
(5, 'f')
'''

li = ['a','b','c','d','e','f']
for i in enumerate(li,10):
    print(i)
'''
(10, 'a')
(11, 'b')
(12, 'c')
(13, 'd')
(14, 'e')
(15, 'f')
'''
View Code

 

面向对象day4的作业和答案

# 1. 类变量(静态属性)和实例变量(对象属性)的区别?
# 2. super的作用?在子类中调用父类的方法
# 一般情况下 子类中有和父类相同的方法名
# 3. isinstance和type的区别并用代码举例说明?
# isinstance能判断对象与类之间的继承关系
# type只能判断这个对象是哪个类创建出来的

# 4. 补全代码
#     ``` python
#     def func(arg):
#         """
#         判断arg是否可以被调用,如果可以则执行并打印其返回值,否则直接打印结果
#         :param arg: 传入的参数
#         """
#         pass

# def func(arg):
#     """
#     判断arg是否可以被调用,如果可以则执行并打印其返回值,否则直接打印结果
#     :param arg: 传入的参数
#     """
#     if callable(arg):
#         ret = arg()
#         print(ret)
#     else:
#         print('else : ',arg)
# class Foo:pass
#
# func(Foo)   # 类可以被调用,而对象不行
# obj = Foo()
# func(obj)

# 5. 补全代码
#     ``` python
#     def func(*args):
#         """
#         计算args中函数、方法、Foo类的对象的个数,并返回给调用者。
#         :param args: 传入的参数
#         """
#         pass
#     ```
# from types import MethodType,FunctionType
# def func(*args):
#     function_count = 0
#     method_count = 0
#     foo_obj = 0
#     for item in args:
#         if isinstance(item,FunctionType):
#             function_count += 1
#         elif isinstance(item,MethodType):
#             method_count += 1
#         elif isinstance(item,Foo):
#             foo_obj += 1
#     return {'function_count':function_count,'method_count':method_count,'foo_obj':foo_obj}
# def func1():pass
# def func2():pass
# class Foo:
#     def method1(self):pass
#     def method2(self):pass
#     def method3(self):pass
# f1 = Foo()
# ret = func(func1,func2,f1.method1,Foo.method1,Foo(),Foo())
# print(ret)


# 6. 看代码写结果并画图表示对象和类的关系以及执行流程
#     ``` python
# class StarkConfig(object):
#     list_display = []
#
#     def get_list_display(self):
#         self.list_display.insert(0,33)
#         return self.list_display
#
# class RoleConfig(StarkConfig):
#     list_display = [11,22]
#
# s1 = StarkConfig()
# s2 = StarkConfig()
#
# result1 = s1.get_list_display()    # self.list_display = [33]
# print(result1)
#
# result2 = s2.get_list_display()   # self.list_display = [33,33]
# print(result2)
#     ```
# 7. 看代码写结果并画图表示对象和类的关系以及执行流程
#     ``` python
class StarkConfig(object):
    list_display = []

    def get_list_display(self):
        self.list_display.insert(0,33)
        return self.list_display

class RoleConfig(StarkConfig):
    list_display = [11,22]

s1 = StarkConfig()
s2 = RoleConfig()

result1 = s1.get_list_display()
print(result1)

result2 = s2.get_list_display()
print(result2)
#     ```
# 8. 看代码写结果并画图表示对象和类的关系以及执行流程
#     ```python
# class StarkConfig(object):
#     list_display = []
#
#     def get_list_display(self):
#         self.list_display.insert(0,33)
#         return self.list_display
#
# class RoleConfig(StarkConfig):
#     list_display = [11,22]
#
# s1 = RoleConfig()
# s2 = RoleConfig()
#
# result1 = s1.get_list_display()
# print(result1)
#
# result2 = s2.get_list_display()
# print(result2)
#     ```
# 9. 看代码写结果
#     ```python
#     class Base(object):
#         pass
#
#     class Foo(Base):
#         pass
#
#     print(issubclass(Base, Foo))  # False
作业和答案

 

面向对象day5作业和答案

# 1. 看代码写结果
#     '''python
#     class Foo(object):
#
#         def __init__(self):
#             self.name = '武沛齐'
#             self.age = 100
#
#     obj = Foo()
#     setattr(Foo, 'email', 'wupeiqi@xx.com')
#
#     v1 = getattr(obj, 'email')
#     v2 = getattr(Foo, 'email')  # 'wupeiqi@xx.com'
#
#     print(v1,v2)  # ('wupeiqi@xx.com','wupeiqi@xx.com')
#     '''



# 2. 如果有以下handler.py文件,补全func:
#     - dir方法能够得到当前文件中的所有成员
#     - 获取handler中名字叫Base的成员
#     - 检查其他成员是否是Base类的子类(不包含Base),如果是则创建对象并添加到objs列表中。

    # ```python
    # # handler.py
# class Base(object):
#     pass
#
# class F1(Base):
#     pass
#
# class F2(Base):
#     pass
#
# class F3(F2):
#     pass
#
# class F4(Base):
#     pass
#
# class F5(object):
#     pass
#
# class F6(F5):
#     pass
#
# import sys
# def func():
#     name_lst = dir(sys.modules[__name__])
#     obj_list = []
#     for name in name_lst:
#         name_addr = getattr(sys.modules[__name__],name)
#         if type(name_addr) is type and issubclass(name_addr,Base) and name_addr is not Base:
#             obj_list.append(name_addr())
#     return obj_list
# ret = func()
# print(ret)

    # ```

# 3.补充代码
#     ```python
#     class Foo(object):
#         def __init__(self):
#             self.name = '武沛齐'
#             self.age = 100
#     obj = Foo()
#     setattr(obj, 'email', 'wupeiqi@xx.com')
#     print(obj.__dict__)
#     请实现:一行代码实现获取obj中所有成员(字典类型)

# 4.写一个类,包含对象属性和方法
# 根据用户的输入找到对应的类成员,如果是方法名就调用,如果是属性就打印
class Foo:
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def eat(self):print('')
    def drink(self):print('')
    def sleep(self):print('')

alex = Foo('alex',20)
while True:
    name = input('>>>')
    if hasattr(alex,name):
        name_addr = getattr(alex, name)
        if callable(name_addr):
             name_addr()
        else:print(name_addr)

# 5.继续完成学生选课系统的作业(必须用到反射)

# 6.预习http://www.cnblogs.com/Eva-J/articles/7228075.html 常用模块一
View Code

 

 posted on 2022-05-12 20:09  编程之路任重道远  阅读(26)  评论(0)    收藏  举报