python3--面向对象--综合练习

发布时间:2018-05-18 23:38:43编辑:Run阅读(4968)

    一 基础知识:

    1  文件操作有哪些模式?请简述各模式的作用


    r:只读

    w:只写

    a:追加

    r+:可读可写

    w+:可写可读

    a+:追加、读

    rb:读取字节

    wb:写入字节

    ab:追加字节

    rb+:字节的可读可写

    wb+:字节的可写可读

    ab+:字节的追加、读


    2  详细说明tuple、list、dict的用法,以及它们的特点


    tuple:用在存储不可变的数据;   特点:有序、可读、不可增加修改、删除

    list:用来存储有序数据;        特点:有序、可进行增删改查

    dict:用来存储成对数据;        特点:无序、以键值对形式存在


    3  解释生成器(generator)与函数的不同,并实现且使用简单generator


    生成器:本质就是迭代器,可以由自己创建,只有需要取值的时候,才会生成值,节省内存空间

    生成器创建方式: 关键字yield

    def func():

        a = 1

        yield a

    g = func()

    for i in g:

        print(i)


    4  如何理解lambda函数/表达式


    lambda函数:匿名函数,用来完成单一功能的函数   lambda x: x**2


    5 a=10

      b=20

      def test(a,b):

         print(a,b)

      c = test(b,a)

      print(c)

      上述代码中,打印出来的值a,b,c分别是什么?为什么?



    a的值为20,实参b的值传给了形参a,所以打印形参a的值就是打印实参b的值

    b的值为10,实参a的值传给了形参b,所以打印形参b的值就是打印实参a的值

    c的值为None,test函数里面没有return关键字,默认返回None


    6   描述一下@property是做什么用的,简单写一个实例并执行


    @property: 将被装饰的方法伪装成属性,常用于封装私有属性

    class Person:

        def __init__(self,name):

            self.__name = name

        @property

        def name(self):

            return self.__name

    a = Person('Mordred')

    print(a.name)


    7  d={'k1':'v1','k2':[1,2,3],('k','3'):{1,2,3}}

      请用程序实现:

      1)输出上述字典中value为列表的key

      2)如果字典中的key是一个元祖,请输出对应的value值。

      3)d[('k','3')]对应的value是一个什么数据类型


    d = {'k1': 'v1', 'k2': [1, 2, 3], ('k', '3'): {1, 2, 3}}

    for i in d:

        if type(d[i]) is list:

            print("value为列表的key:", i)

        elif type(i) is tuple:

            print("key是一个元组,对应的value:", d[i])

    print(type(d[('k', '3')]))


    8  如果不使用@wrapper装饰器,请在a()之前加入一句代码,达到相同的效果

    def wrapper(func):

        def inner(*arg, **kwargs):

            func(*arg, **kwargs)

        return inner

     

    @wrapper

    def a(arg):

        print(arg)

     

    a()


    def wrapper(func):

        def inner(*arg, **kwargs):

            func(*arg, **kwargs)

        return inner


    def a(arg):

        print(arg)

        

    a = wrapper(a)

    a()

    插入的代码为:a = wrapper(a)



    9  请处理文件7th_questions,输出所有以'T'开头的行

    7th_questions文件内容如下:

    One year like any old other year
    In a week like any week
    Monday lying down, half asleep
    People doing what people do
    Loving,working,and
    getting through no portraits on the walls Of Seventh Avenue
    Then Tuesday came and went
    Like a helicopter overhead
    The letter that she left, cold addressed in red
    Tuesday came and went one
    One September
    When will she come again
    The thing about memories
    They're sure and bound to fade
    Except for the stolen souls Left upon her blade
    Is Monday coming back That's what Mondays do
    They Turn and Turn around
    Afraid to see it through
    Then Tuesday came and went
    Like a helicopter overhead
    The letter that she left, cold addressed in red
    Tuesday came and went one
    One September
    When will she come again
    Tuesday came and went one
    One September, when?
    Cold and dressed in red
    How could I forget
    Tuesday came and went
    Like a helicopter overhead
    Will she come again?

    with open('7th_questions',encoding='utf-8') as f1:

        for line in f1:

            if line.startswith('T'):

                print(line.strip())


    10  读test2.py登陆文件夹中的代码,请为这段代码画流程图

    test2.py文件内容如下: 

    def login():
        print("这是一个登陆页面!")
     
    def logout():
        print("这是一个退出页面!")
     
    def home():
        print("这是网站主页面!")
     
    def article():
        print("这是网站文章页面")
     
    def editor():
        print("这是网站编辑页面!")
     
    def add():
        print("这是网站添加页面!")
     
    def delete():
        print("这是网站删除页面!")
     
    def admin():
        print("这是网站管理员页面!")




    11 默写10个字符串对象的内置方法,描述它的作用


    str.split() 指定元素对字符串进行分割,返回一个列表

    str.strip()  指定元素从两头对str进行循环去除

    str.center()  剧中并填充,可以指定填充物

    str.capitalize()  首字母大写,其余字母小写

    str.title()   所有以非字母隔开的单词的首字母大写,其余字母小写

    str.startswith()  判断str是否以某个字符开头

    str.encode()  对str进行编码

    str.find()   查找指定字符在str中的位置

    str.isdigit() 判断字符串是否由数字组成

    str.lower()  将str里的字母全部小写


    12  有如下代码,写出调用的顺序以及结果

    def f1():

        print('funcname is f1')

     

    def f2():

        print('funcname is f2')

        return 1

     

    def f3(func1):

        ll = func1()

        print('funcname is f3')

        return ll

     

    print(f3(f2))


    调用顺序:先调用f3,再调用f2

    结果:

    funcname is f2

    funcname is f3

    1



    13   创建一个闭包函数需要满足哪几点?


    1.函数嵌套,最少有2层,一个外层函数,一个内层函数

    2.内层函数对外层函数变量(非全局变量)的引用



     

    14  将时间打印出成一个2017/10/01 18:08:15的格式

      将 "2017-11-18 17:43:43" 转换为结构化时间


    import time

    struct_time = time.strptime("2017-11-18 17:43:43", "%Y-%m-%d %H:%M:%S")

    print("结构化时间:", struct_time)

    str_time = time.strftime("%Y/%m/%d %H:%M:%S", struct_time)

    print("格式化时间:", str_time)



     

    15  用什么模块能知道文件夹存不存在?

        怎么获取这个文件夹的大小?


    os模块

    os.path.exists()  判断文件夹存不存在

    os.path.getsize()  取这个文件的大小


     

    16 简单解释Python中static method(静态方法)和class method(类方法)

     

    static method(静态方法):既不使用对象的属性,也不使用类的属性

    class method(类方法):不使用对象的属性,只使用类的属性



    17.请描述一下__new__方法和__init__的区别以及是做什么的


    __new__:构造方法,创造实例

    __init__:初始化方法,实例化过程中自动调用,对实例进行初始化

    先用__new__方法创造一个实例,再用__init__方法对实例进行初始化



     

    18   有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?(编程题)

     

    lis = [1, 2, 3, 4]

    ret_list = []

    for i in lis:

        for j in lis:

            for k in lis:

                if i != j and i != k and j != k:

                    s = str(i) + str(j) + str(k)

                    ret_list.append(int(s))

    print('个数为:%s   所有数字:%s'%(len(ret_list), ret_list))



    19  有这个一个test2文件,文件中模拟一个网站的页面定义了多个函数,现在有个需求是不使用if,else条件语句,进行判断我想访问那个页面

    例如:

    请输入你要访问的url>>>:login

    他就提示我们   ----  这是一个登陆页面!说明登陆成功了

    def login():
        print("这是一个登陆页面!")
    
    def logout():
        print("这是一个退出页面!")
    
    def home():
        print("这是网站主页面!")
    
    def article():
        print("这是网站文章页面")
    
    def editor():
        print("这是网站编辑页面!")
    
    def add():
        print("这是网站添加页面!")
    
    def delete():
        print("这是网站删除页面!")
    
    def admin():
        print("这是网站管理员页面!")
        
    import sys
    url = input('url>>>').strip()
    getattr(sys.modules[__name__], url)()


     

    20  实现一个发红包的编程题(使用random)编程题

    import random
    def content(ss):
        ss = int(ss)
        print('红包总金额为:{}'.format(ss))
        count = 0
        while True:
            suiji = random.randint(1, int(ss))
            count += 1
            print('第{}次抢到{}'.format(count, suiji))
            ss -= suiji
            if ss == 0:
                print('红包已发完!'.format(ss))
                break
    content(10)

     

    二 面向对象

     

    1  请简述类、对象、实例化、实例这些名词的含义


    类:具有相同属性和方法的一系列事物

    对象:具体描述某一类的个体

    实例化:创造实例(对象)的过程

    实例:一个实例就是一个对象


    2  面向对象的三大特性是什么?


    继承  封装  多态


    3  有一个类定义:

        class Person:

            def __init__(self,name,age):

                self  name = name

                self  age = age

     

        1)初始化10个不同的对象

        2)求最高age的对象的name


    class Person:

        def __init__(self, name, age):

            self.name = name

            self.age = age

    l1 = []

    for i in range(1,11):

        l1.append(Person('qwe%' % i, i*10))

    print(max(l1,key=lambda x: x.age).name)




    4   模拟cs游戏

        1)人物角色分为警察和匪徒两种,定义成两个类

            所有的警察的角色都是police

            每个警察都有自己独有名字,生命值,武器,性别

            每个都可以开枪攻击敌人,切攻击目标不能是police

     

     

            所有的警察的角色都是terrorist

            每个匪徒都有自己独有名字,生命值,武器,性别

            每个都可以开枪攻击敌人,切攻击目标不能是terrorist

     

        2)实例化一个警察,一个匪徒,警察攻击匪徒,匪徒掉血

     

        3)提取警察类和匪徒类相似之处定义成一个父类,使用继承的方式减少代码重复


    class Person:
        def __init__(self, name, hp, weapon, sex):
            self.name = name
            self.hp = hp
            self.weapon = weapon
            self.sex = sex
    
    class Police(Person):
        def bang(self, person):
            if isinstance(person, Police):
                print('不能攻击自己人')
            else:
                person.hp -= self.weapon.agr
    class Terrorist(Person):
        def bang(self, person):
            if isinstance(person, Terrorist):
                print('不能攻击自己人')
            else:
                person.hp -= self.weapon.agr
    
    class Weapon:
        def __init__(self, name, agr):
            self.name = name
            self.agr = agr
    
    gun1 = Weapon('gun1', 30)
    gun2 = Weapon('gun2', 20)
    police = Police('Sam', 100, gun1, '男')
    police1 = Police('a', 100, gun1, '男')
    terrorist = Terrorist('拉登', 100, gun2, '男')
    police.bang(terrorist)
    police.bang(police1)
    print(terrorist.hp)


    5 读代码

     

    5(1)

    class Base:

        def f1(self):

            self  f2()

     

        def f2(self):

            print('      ')

     

    class Foo(Base):

        def f2(self):

            print('9999')

     

    obj = Foo()

    obj  f1()

     

    问题1:面向对象中的self指的什么?

    问题2:运行结果并简述原因

     

    self 指定的是实例自身

    运行结果:

    9999

    原因:实例在查找属性或方法时的顺序:实例自身的命名空间  类的命名空间  父类的命名空间

    obj的查找顺序: obj自身的命名空间没有f1

                    Foo的命名空间中没有f1

                    在Base的命名空间中找到f1

                    obj自身的命名空间没有f2

                    然后在Foo的命名空间中找到f2

                    执行f2,输出9999

     


    5

    class JustCounter:

       __secretCount = 0

     

       def count(self):

           self  __secretCount += 1

           print(self  __secretCount)

     

    class Bars(JustCounter):

     

        def count(self):

            print(self  __secretCount)

     

     

    counter1 = JustCounter()

    counter2 = Bars()

     

    counter1  count()

    counter2  count()

    print (counter1  __secretCount)

     

    问题1:简述counter1  count()执行流程?

    问题2:运行结果并简述原因

     

    counter1.count()执行流程:

                1.判断counter1属于哪个类

                2.在JustCounter中查找count方法

                3.调用count方法,并将counter1传递给self

                4.执行self.__secretCount += 1,调用JustCounter的属性__secretCount并加1,self               创建一个属性__secretCount,修改后的值赋给self.__secretCount

                5.执行print(self.__secretCount),打印self._JustCounter__secretCount的值

                6.在程序运行过程中,解释器会把self.__secretCount变形为                                     self._JustCounter__secretCount

                               

    运行结果: 先打印1,再报错

    原因:解释器会把self.__secretCount变形为self._当前类的类名__secretCount

            counter1在JustCounter类中找到count方法,所以counter1.__secretCount变形为counter1._JustCounter__secretCount,打印1

            counter2在Bars类中找到count方法,所以counter2.__secretCount变形为counter2._Bars__secretCount,而_Bars__secretCount属性不存在,所以报错

     

     

    附加思考题:

        有一个类的init方法如下:

        class Person:

            def __init__(self,name,age,sex,weight):

                self  name = name

                self  sex = sex

                self  age = age

                self  weight = weight

        假设有100个person的对象,

        若两个对象的obj1,obj2的name和sex属性相同

        即obj1  name==obj2  name and obj1  sex==obj2  sex

        我们认为两个对象为同一个对象,已知一个列表中的100个对象,对这100个对象进行去重。

        提示:

            重写Person类重的两个内置方法

    class Person:
        def __init__(self,name,age,sex,weight):
            self.name = name
            self.age = age
            self.sex = sex
            self.weight = weight
    
        def __hash__(self):
            return hash(self.name+self.sex)
    
        def __eq__(self, other):
            if self.name == other.name and self.sex == other.sex:return True
    
    p_lst1 = []
    for i in range(98):
        p_lst1.append(Person('egon' + str(i),i,'male',i))
    p_lst1.append(Person('egon50',200,'male',167))
    p_lst1.append(Person('egon51',300,'male',170))
    print(len(p_lst1))
    print(len(set(p_lst1)))


关键字