欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

第三模块:面向对象&网络编程基础-第1章 面向对象-练习题(编程题)

程序员文章站 2022-06-26 15:15:11
1.请用面向对象的形式优化以下代码class Sql: host= '127.0.0.1' port=3306 db='db1' charset='utf8' sql='select * from tb1;' proc_name='存储过程的名字' def __init__(self,*args): self.args=args def connect(self): pass def exc(self)...

1.请用面向对象的形式优化以下代码

class Sql:
    host= '127.0.0.1'
    port=3306
    db='db1'
    charset='utf8'
    sql='select * from tb1;'
    proc_name='存储过程的名字'
    def __init__(self,*args):
        self.args=args
    def connect(self):
        pass
    def exc(self):
        if self.args == self.sql:
            conn = self.connect(self.host,self.port,self.db,self.charset)
            res=conn.execute(self.sql)
            return res
        elif self.args == self.proc_name:
            conn = self.connect(self.host, self.port, self.db, self.charset, self.proc_name)
            res = conn.call_proc(self.sql)
            return res
ex=Sql('select * from tb1;')
print(ex.__dict__)

2.请简单解释Python中 staticmethod(静态方法)和 classmethod(类方法), 并分别补充代码执行下列方法。
非绑定方法:不与类或对象绑定staticmethod
绑定到类的方法:在类内定义的被装饰器@classmethod修饰的方法

class A(object):

   def foo(self, x):
       print("executing foo(%s, %s)" % (self,x))

   @classmethod
   def class_foo(cls, x):
       print("executing class_foo(%s, %s)" % (cls,x))

   @staticmethod
   def static_foo(x):
       print("executing static_foo(%s)" % (x))

a = A()
a.foo("egon")
A.class_foo(1)
a.static_foo(1)

3.编写程序, 如下有三点要求:
1.自定义用户信息数据结构, 写入文件, 然后读取出内容, 利用json模块进行数据的序列化和反序列化
e.g
{
“egon”:{“password”:“123”,‘status’:False,‘timeout’:0},
“alex”:{“password”:“456”,‘status’:False,‘timeout’:0},
}
2.定义用户类,定义方法db,例如 执行obj.db可以拿到用户数据结构
3.在该类中实现登录、退出方法, 登录成功将状态(status)修改为True,
退出将状态修改为False(退出要判断是否处于登录状态).
密码输入错误三次将设置锁定时间(下次登录如果和当前时间比较大于10秒即不允许登录)
‘’’

import json
import time
class User:
    def __init__(self, name, password):
        self.name = name
        self.password = password
        self.status = False
        self.timeout = 0

    @property
    def db(self):
        with open(self.name+'.txt', 'r', encoding='utf-8') as f:
            data = json.load(f)
        return data

    def save(self):
        obj={}
        obj[self.name]={'password':self.password,'status':self.status,'timeout':self.timeout}
        with open(self.name+'.txt', 'w', encoding='utf-8') as f:
            json.dump(obj,f)

    def login(self):
        with open(self.name+'.txt', 'r+', encoding='utf-8') as f:
            data = json.load(f)
            count = 0
            while count < 3:
                password = input('password>>:').strip()
                if password != data[self.name]['password']:
                    count += 1
                    continue
                else:
                    if data[self.name]['timeout'] != 0:
                        if time.time() - data[self.name]['timeout'] > 10:
                            print('不允许登录了!超时')
                            break
                        else:
                            data[self.name]['status'] = True
                            f.seek(0)
                            f.truncate()
                            json.dump(data, f)
                            print('----welcome----')
                            break
                    else:
                        data[self.name]['status'] = True
                        f.seek(0)
                        f.truncate()
                        json.dump(data, f)
                        print('----welcome----')
                        break

            else:
                data[self.name]['timeout']=time.time()
                f.seek(0)
                f.truncate()
                json.dump(data,f)


    def quit(self):
        with open(self.name+'.txt', 'r+', encoding='utf-8') as f:
            data = json.load(f)
            if data[self.name]['status'] == True:
                data[self.name]['status'] = False
                f.seek(0)
                f.truncate()
                json.dump(data, f)
            else:
                print('您是退出状态!')


alex=User('alex','123')
egon=User('egon','456')
alex.save()
egon.save()
print(alex.db)
print(egon.db)

4.编写程序, A 继承了 B, 俩个类都实现了 handle 方法,
在 A 中的 handle 方法中调用 B 的 handle 方法

class B:
    def handle(self):
        print("i am b")

class A(B):
    def handle(self):
        super().handle()
        print("i am a")

a = A()
a.handle()

5.编写程序, 编写一个学生类, 要求有一个计数器的属性, 统计总共实例化了多少个学生

class Student:
    count = 0
    def __init__(self,name,age,sex):
        self.name = name
        self.age = age
        self.sex = sex

        Student.count += 1
    def count_num(self):
        print("实例化了%s个学生" %Student.count)
s1 = Student("a",18,"male")
s2 = Student("b",16,"female")
s3 = Student("c",15,"male")
s1.count_num()

6.使用实例进行 获取、设置、删除 数据, 分别会触发类的什么私有方法

class A(object):
    def __getitem__(self, item):
        return self.__dict__.get(item)
    def __setitem__(self, key, value):
        self.__dict__[key] = value
    def __delitem__(self, key):
        del self.__dict__[key]

a = A()
#设置属性
a["key"] = "val"
print(a.__dict__)
b = a["key"]
print(b)
#删除属性
del a["key"]
print(a.__dict__)

7.人狗大站,2个角色,人和狗,
游戏开始后,生成2个人,3条狗,互相混战,人被狗咬了会掉血,狗被人打了也掉血,
狗和人的攻击力,具备的功能都不一样
class Animal:
def init(self,name,blood,attack):
self.name = name
self.blood = blood
self.attack = attack
def attribute(self,enemy):
self.blood -= enemy.attack
class Dog(Animal):
def attribute(self,enemy):
super().attribute(enemy)
print("%s attack %s" %(self.name,enemy.name))
class People(Animal):
def attribute(self,enemy):
super().attribute(enemy)
print("%s attack %s" %(self.name,enemy.name))

d1 = Dog(“二哈”,100,10)
p1 = People(“大壮”,100,20)
d1.attribute(p1)
print(d1.blood)
8.请编写一段符合多态特性的代码

import abc
class Animals(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def talk(self):
        pass
class People(Animals):
    def talk(self):
        print("say hello")
class Dog(Animals):
    def talk(self):
        print("say wangwang")
class Cat(Animals):
    def talk(self):
        print("say miaomiao")
people = People()
dog = Dog()
cat = Cat()

def func(animals):
    animals.talk()
func(people)
func(dog)
func(cat)

9.请执行以下代码,解释错误原因,并修正错误

class Dog(object):

   def __init__(self,name):
       self.name = name

   @property
   def eat(self):
       print(" %s is eating" %self.name)

d = Dog("ChenRonghua")
d.eat

本文地址:https://blog.csdn.net/qq_36993243/article/details/110423181