码迷,mamicode.com
首页 > 其他好文 > 详细

面向对象练习2

时间:2017-04-24 19:46:55      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:装饰器   pre   htm   当前时间   ati   函数名   赋值语句   写入文件   默认   

题目一:总结

1.什么是绑定到对象的方法,如何定义,如何调用,给谁用?有什么特性?

类内定义的函数,不经装饰器装饰,被实例化对象调用,会默认传入一个self参数,对象将会传递给self;

定义方式比较普通‘def 函数名(self):’;

调用方式‘对象.函数名()’;

类和对象都可以调用,被对象调用称为绑定方法。

 

2.什么是绑定到类的方法,如何定义,如何调用,给谁用?有什么特性?

类内部定义的函数,经过@classmethod装饰器装饰,会默认传入一个cls参数,调用该方法的类将传递给cls;

定义方式‘def 函数名(cls):’;

调用方式‘类名.函数名()’;

主要是给类调用,对象也可以强行调用,但是还算是对象所属类的调用,所以一般不推荐。

 

3.什么是解除绑定的函数,如何定义,如何调用,给谁用?有什么特性?

同样是类内部定义的函数,经过@staticmethod装饰器装饰,没有默认传入的参数;

定义方式‘def 函数名()’;

调用方式‘类名.函数名()’;

仅提供给类调用,不考虑给对象使用,可以比作类的另外一种实例化方式。

 

4.什么是property,如何定义,如何使用,给谁用,什么情况下应该将一个属性定义成property,有什么好处?

property译为特征,将有变量特征的函数进行@property装饰,直接可以通过函数名调用;

可以将隐藏属性定义函数形成借口,便于调用;

调用方便,直接通过‘对象.函数名’调用。

 

以上题目详细参考http://www.cnblogs.com/xuyaping/p/6723862.html中静态方法和类方法的总结

 

题目二:

一:自定义用户信息数据结构,写入文件,然后读出内容,利用eval重新获取数据结构

with open(‘user.db‘,‘w‘) as write_file:		#创建并以写入的方式打开一个文件user.db
    write_file.write(str({			#在user.db中加入两个用户信息以字典的方式储存
        "egon":{"password":"123",‘status‘:False,‘timeout‘:0},
        "alex":{"password":"456",‘status‘:False,‘timeout‘:0},
        }))

with open(‘user.db‘,‘r‘) as read_file:		#以只读的方式打开一个文件user.db
    data=read_file.read()			#读取user.db中的数据						
    d=eval(data) 				#将user.db中的数据转为字典
    print(d[‘egon‘][‘password‘])		#打印字典中egon的password 对应value
    print(d[‘egon‘][‘status‘])
    print(d[‘egon‘][‘timeout‘])

 

二:定义用户类,定义属性db,执行obj.db可以拿到用户数据结构

class User: 					#定义User类
    db_path=‘user.db‘
    def __init__(self,username): 		#在实例化User类时,传入Username参数的值
        self.username=username
    @property					#将db()方法作为属性,让用户调用
    def db(self):
        data=open(self.db_path,‘r‘).read()	#以只读的方式打开文件user.db
        return eval(data)			#以字典的方式返回user.db中的内容
u=User(‘egon‘)					#实例化对象u,传入egon
print(u.db[‘egon‘])				#打印又u.db()返回的字典中,对应egon的value
print(u.db[‘egon‘][‘password‘])			#打印又u.db()返回的字典中,对应egon的password,value

 

三:分析下述代码的执行流程 

import time
class User:
    db_path = ‘user.db‘
    def __init__(self, name):
        self.name = name
    @property
    def db(self):
        with open(self.db_path, ‘r‘) as read_file:
            info = read_file.read()
            return eval(info)
    @db.setter
    def db(self, value):
        with open(self.db_path, ‘w‘) as write_file:
            write_file.write(str(value))
            write_file.flush()

def login(self):  # 3、self接收对象u1
    data = self.db  # 4、u1调用db属性,寻找实例化中的db属性,返回值为‘user.db’文件中的数据结构,并赋值给date
    if data[self.name][‘status‘]:  # 5、判断对象u1的status字段bool值(等于date[‘egon‘][‘status]),为Ture执行下面代码-->#6,否则跳过-->#8
        print(‘已经登录‘)  # 6、为真打印
        return True  # 7、返回Ture,结束函数-->#end
    if data[self.name][‘timeout‘] < time.time():  # 8、判断对象u1的timeout字段(等于date[‘egon][‘timeout‘])是否小于当前时间,小于执行一下代码-->#9,否则执行else-->#22
        count = 0  # 9、设置计数器count
        while count < 3:  # 10、当计数器<3时执行循环
            passwd = input(‘password>>: ‘)  # 11、请用户输入密码,赋值给passwd
            if not passwd: continue  # 12、如果passwd为空,跳出执行下一次循环-->10,否则继续-->#13
            if passwd == data[self.name][
                ‘password‘]:  # 13、判断passwd是否等于date[‘egon‘][‘password‘],为Ture执行以下代码-->#14,否则-->#18
                data[self.name][‘status‘] = True  # 14、将date中u1[‘egon‘][‘status‘]改为Ture
                data[self.name][‘timeout‘] = 0  # 15、将date中u1[‘egon‘][‘timeout‘]改为0
                self.db = data  # 16、赋值语句就调用u1的db属性经@db.setter装饰的方法,将修改写入文件中
                break  # 17、跳出循环-->#end
            count += 1  # 18、密码不对,计数器+1,继续循环-->#10
        else:  # 19、用户输入密码一直错误,计数器超过循环要求,循环正常结束,执行以下代码-->#20
            data[self.name][‘timeout‘] = time.time() + 10  # 20、将date中u1[‘egon‘][‘timeout‘]改为当前时间+十秒  
            self.db = data  # 21、将修改结果,写入文件中-->#end
    else:  # 22、对象u1的timeout字段大于当前时间
        print(‘账号已经锁定10秒‘)  # 22、打印提示--#end

u1 = User(‘egon‘)  # 1、实例化对象u1,name=‘egon
u1.login()  # 2、u1调用login方法-->3

u2 = User(‘alex‘)
u2.login()

 

要求四:根据上述原理,编写退出登录方法(退出前要判断是否是登录状态),自定义property,供用户查看自己账号的锁定时间

import time
class User:
    db_path = ‘user.db‘
    def __init__(self, name):
        self.name = name
    @property
    def db(self):
        with open(self.db_path, ‘r‘) as read_file:
            info = read_file.read()
            return eval(info)
    @db.setter
    def db(self, value):
        with open(self.db_path, ‘w‘) as write_file:
            write_file.write(str(value))
            write_file.flush()
    @property
    def check_lock_time(self):
        with open(self.db_path, ‘r‘) as read_file:
            info = read_file.read()
            info = eval(info)
            if info[self.name][‘timeout‘] > time.time():
                time_diff = info[self.name][‘timeout‘] - time.time()
                print(‘您的账号剩余锁定时间%s秒‘ % int(time_diff))
            else:
                print(‘您的账号未被锁定‘)

    def login(self):
        data = self.db
        if data[self.name][‘status‘]:
            print(‘已经登录‘)
            return True
        if data[self.name][‘timeout‘] < time.time():
            count = 0
            while count < 3:
                passwd = input(‘password>>: ‘)
                if not passwd: continue
                if passwd == data[self.name][‘password‘]:
                    data[self.name][‘status‘] = True
                    data[self.name][‘timeout‘] = 0
                    self.db = data
                    break
                count += 1
            else:
                data[self.name][‘timeout‘] = time.time() + 10
                self.db = data
        else:
            print(‘账号已经锁定10秒‘)

    def logout(self):
        date = self.db
        if date[self.name][‘status‘]:
            date[self.name][‘status‘] = False
            self.db = date
            print(‘您已登出‘)
            return True


u1 = User(‘egon‘)
u1.login()
u1.check_lock_time
u1.logout()

  

面向对象练习2

标签:装饰器   pre   htm   当前时间   ati   函数名   赋值语句   写入文件   默认   

原文地址:http://www.cnblogs.com/xuyaping/p/6758437.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!