Python学习之Day05学习(定制数据对象,面向对象)

一、前情回顾

根据数据清洗确定排序列表不重复性元素,采用了如下案例

python 复制代码
# coding=utf-8

###  有关清理数据的函数(数据清洗)
def santize(time_string):
    if '-' in time_string:
        spliter='-'
    elif ':' in time_string:
        spliter=':'
    else:
        return time_string
    minutes,seconds=time_string.split(spliter)
    return(minutes+'.'+seconds)


def get_coach_data(filename):
    try:
        with open(filename) as f:
            data = f.readline()
        return data.strip().split(',')
    except IOError as error:
        print('File error:'+str(error))
        return (None)

sarch=get_coach_data('sarah.txt')
sarch_name,sarch_dob=sarch.pop(0),sarch.pop(0)
print(sarch_name+"'s fasterst times are"+str(sorted(set([santize(t) for t in sarch]))[0:3]))

二、数据类型之字典表示

使用字典时,键对于字典来说无非就是唯一的

vbscript 复制代码
>>    num={}

>>    num=dict()

>>    num
{}

>>    type(num)
<class 'dict'>

>>    num['one']=1

>>    num['two']=2

>>    num
{'one': 1, 'two': 2}

>>    num['one']
1

>>    num['two']
2

>>    num['nums']=[1,2,3,4,5,6]

>>    num
{'one': 1, 'two': 2, 'nums': [1, 2, 3, 4, 5, 6]}

>>    num['nums'][0]
1

>>    num['nums'][-1]
6

优前情回顾内容:

python 复制代码
def get_coach_data(filename):
    try:
        with open(filename) as f:
            data = f.readline()
        return data.strip().split(',')
    except IOError as error:
        print('File error:'+str(error))
        return (None)

sarch=get_coach_data('sarah.txt')
sarch_data={}
sarch_data['name']=sarch.pop(0)
sarch_data['dob']=sarch.pop(0)
sarch_data['times']=sarch
print(sarch_data['name']+"'s fastest time are:'"+str(sorted(set(santize(t) for t in sarch_data['times']))[0:3]))

优化字典作为返回值,重写代码:

python 复制代码
def santize(time_string):
    if '-' in time_string:
        spliter='-'
    elif ':' in time_string:
        spliter=':'
    else:
        return time_string
    minutes,seconds=time_string.split(spliter)
    return(minutes+'.'+seconds)


def get_coach_data(filename):
    try:
        with open(filename) as f
            data = f.readline()
        templ=data.strip().split(',')
#####修改部分代码#####
        return({
            'name':templ.pop(0),
            'dob':templ.pop(0),
            'times':str(sorted(set(santize(t) for t in templ))[0:3])
        })
    except IOError as error:
        print('File error:'+str(error))
        return (None)

james=get_coach_data('james.txt')
sarch=get_coach_data('sarah.txt')
print(james['name']+"'s fastest time are:'"+james['times'])
print(sarch['name']+"'s fastest time are:'"+sarch['times'])

三、将对象打包到类中

  • 定义一个类
  • 类的定义图解
  • 类的对象实例
  • 针对self如何使用
python 复制代码
class Athelete:
    def __init__(self,value=0):
        self.thing=value
    def how_big(self):
        return len(self.thing)
d=Athelete("halo go!!!")
print(d.how_big())
print(d.thing)

字典和列表类型的转换

python 复制代码
a={}
lol=[['a','b'],['c','d'],['e','f']]
l=dict(lol)
print(l)        ##{'a': 'b', 'c': 'd', 'e': 'f'}

字典和元组的转换

python 复制代码
lot=[('a','b'),('c','d'),('e','f')]
dict(lot)       ##{'a': 'b', 'c': 'd', 'e': 'f'}

字典和字符串(要求双字符)转换

python 复制代码
los=['ab','bc','cd','de']
l=dict(los)
print(l)        ## {'a': 'b', 'b': 'c', 'c': 'd', 'd': 'e'}

字典中元素使用

python 复制代码
## 往字典中添加元素
d={}
d['l1']=1
print(d)    ### {'l1': 1}
d['l2']=2
print(d)    ### {'l1': 1, 'l2': 2}



## 修改元素的值
d={}
d={"l1":1,"l2":2}
d.update({"l3":3,"l4":4})
print(d)    ##{'l1': 1, 'l2': 2, 'l3': 3, 'l4': 4}

##  删除元素中的值
del d['l4']
print(d)    ## {'l1': 1, 'l2': 2, 'l3': 3}

## 判断是否在键值对存在相应的键
print("l1" in d)    ## True

## 清空所有元素
d.clear()    ## {}





## 获取字典中key和value的情况
print(d.keys()) ## dict_keys(['l1', 'l2', 'l3'])
print(d.values())   ## dict_values([1, 2, 3])
print(list(d.values())) ## [1, 2, 3]
print(d.items())    ## dict_items([('l1', 1), ('l2', 2), ('l3', 3)])
print(list(d.items()))  ## [('l1', 1), ('l2', 2), ('l3', 3)]


## 将压缩的列表组合成一个字典
l1=[1,2,3]
l2=['one','two','three']
zipped=zip(l1,l2)
print(dict(zipped))     ## {1: 'one', 2: 'two', 3: 'three'}


## 字典拷贝
d={'l1':1,'l2':2,'l3':3}
d2=d
d.update({'l4':4})
print(d2)    ## {'l1': 1, 'l2': 2, 'l3': 3, 'l4': 4}


d={'l1':1,'l2':2,'l3':3}
d2=d.copy()
d.update({'l4':4})
print(d2)    ## {'l1': 1, 'l2': 2, 'l3': 3}

数据类型之集合

set集合的使用(去重)

有关字典和列表的扩充

python 复制代码
### 推倒单词的个数
word='letters'
letters_counts={letter:word.count(letter) for letter in set(word)}
print(letters_counts)
'''
{'e': 2, 's': 1, 'l': 1, 'r': 1, 't': 2}
'''

## 推倒并判断集合
a_set={1,2,3,4,5,6}
a_set={number for number in range(1,6) if number%2==1}
print(a_set)    '''  {1, 3, 5} '''

a_set={1,2,3,4,5,6}
a_set={number for number in range(1,6) if number%3==1}
print(a_set)    '''{1, 4}'''

数据类型的总结

python 复制代码
## 将列表组合成元组
num=[1,2,3]
name=["l1","l2","l3","l4"]
english=["one","two","three","four","five"]
tol=num,name,english
print(tol)      ## ([1, 2, 3], ['l1', 'l2', 'l3', 'l4'], ['one', 'two', 'three', 'four', 'five'])



## 组合成一个统一的列表
tol=[num,name,english]
print(tol)  ## [[1, 2, 3], ['l1', 'l2', 'l3', 'l4'], ['one', 'two', 'three', 'four', 'five']]


## 字典的组合
dol={"num":num,"name":name,"english":english}
print(dol)      ## {'num': [1, 2, 3], 'name': ['l1', 'l2', 'l3', 'l4'], 'english': ['one', 'two', 'three', 'four', 'five']}


## 复杂数据的获取
house={(44.79,-93.14,285):'my_house',(38.97,-77.04,13):'The white house'}
print(house[44.79,-93.14,285])  ## my_house



##  关于==和is的区别
== 比较值是否相等(比较内存地址),而is则用于比较数据类型
a=1
b=1.0
print(a==b) ## True
print(a is b)   ## False

c=1
print(a==c)     #True
print(a is c)   #True



## 组合打印列表--->元组
cells=[(rows,cols) for rows in row if rows%2==1 for cols in col if cols%2==1]
for cell in cells:
    print(cell)

for row,cols in cells:
    print(row,cols)

面相对象概念及使用

使用对象优化demo,将字典数据转换成对象的形式进行存储

python 复制代码
class Athelete:
    def __init__(self,a_name,a_job=None,a_time=[]):
        self.name=a_name
        self.job=a_job
        self.time=a_time
    def top3(self):
        return sorted(set([santize(t) for t in self.time]))[0:3]

def santize(time_string):
    if '-' in time_string:
        spliter='-'
    elif ':' in time_string:
        spliter=':'
    else:
        return time_string
    minutes,seconds=time_string.split(spliter)
    return(minutes+'.'+seconds)

def get_coach_data(filename):
    try:
        with open(filename) as f:
            data = f.readline()
        templ=data.strip().split(',')
        # return({
        #     'name':templ.pop(0),
        #     'dob':templ.pop(0),
        #     'times':str(sorted(set(santize(t) for t in templ))[0:3])
        # })
        return (Athelete(templ.pop(0),templ.pop(0),templ))
    except IOError as error:
        print('File error:'+str(error))
        return (None)

james=get_coach_data("james.txt")
print(james.name+"'s faster are:"+str(james.top3()))

扩展一个增加时间的版本函数

python 复制代码
class Athelete:
    def __init__(self,a_name,a_job=None,a_time=[]):
        self.name=a_name
        self.job=a_job
        self.time=a_time
    def top3(self):
        return sorted(set([santize(t) for t in self.time]))[0:3]

    ### 扩展增加时间API
    def add_time(self,time_value):
        self.time.append(time_value)

    def add_times(self,list_of_times):
        self.time.extend(list_of_times)
def santize(time_string):
    if '-' in time_string:
        spliter='-'
    elif ':' in time_string:
        spliter=':'
    else:
        return time_string
    minutes,seconds=time_string.split(spliter)
    return(minutes+'.'+seconds)

def get_coach_data(filename):
    try:
        with open(filename) as f:
            data = f.readline()
        templ=data.strip().split(',')
        # return({
        #     'name':templ.pop(0),
        #     'dob':templ.pop(0),
        #     'times':str(sorted(set(santize(t) for t in templ))[0:3])
        # })
        return (Athelete(templ.pop(0),templ.pop(0),templ))
    except IOError as error:
        print('File error:'+str(error))
        return (None)

# james=get_coach_data("james.txt")
# print(james.name+"'s faster are:"+str(james.top3()))
# james.add_times(['2.22','1-11','3:66'])
# print(james.top3())

varos=Athelete('Vara vi')
varos.add_times(['3.88','1-11','6:88'])
print(varos.top3())     ## ['1.11', '3.88', '6.88']

面向对象之继承类

python 复制代码
class AthleteList(list):
    ## 属性
    def __init__(self,a_dob=None,a_times=[]):
        ## 初始化父类信息
        list.__init__([])
        self.name=a_dob
        self.times=a_times
        self.extend(a_times)
    ## 方法
    def top3(self):
        return sorted(set([santize(t) for t in self]))[0:3]




def santize(time_string):
    if '-' in time_string:
        spliter='-'
    elif ':' in time_string:
        spliter=':'
    else:
        return time_string
    minutes,seconds=time_string.split(spliter)
    return(minutes+'.'+seconds)

def get_coach_data(filename):
    try:
        with open(filename) as f:
            data = f.readline()
        templ=data.strip().split(',')
        # return({
        #     'name':templ.pop(0),
        #     'dob':templ.pop(0),
        #     'times':str(sorted(set(santize(t) for t in templ))[0:3])
        # })
        return (AthleteList(templ.pop(0),templ.pop(0),templ))
    except IOError as error:
        print('File error:'+str(error))
        return (None)

# james=get_coach_data("james.txt")
# print(james.name+"'s faster are:"+str(james.top3()))
# james.add_times(['2.22','1-11','3:66'])
# print(james.top3())


## 通过自定义对象提供了对象的可扩展性

varos=AthleteList('Vara vi')
print(varos)
varos.append('1.31')
print(varos.top3())

varos.extend(['2.22','1-21','2:66'])
print(varos)                    ## ['1.31', '2.22', '1-21', '2:66']
print(varos.top3())             ## ['1.21', '1.31', '2.22']

四、面向对象

propetry和attribute方法

python 复制代码
### 案例实现
### demo1 实现对象的定义和赋值
class Person():
    def __init__(self,name):
        self.name=name
xm=Person("xiaoming")       ## 实例化--->对象
Person.__init__(xm,'xiao ming')

print(type(xm))         ## <class '__main__.Person'>
print(xm.name)          ## xiaoming

print(id(xm))             ## 2380080119568
print(hex(id(xm)))       ## <class '__main__.Person'>



### demo2 重写一个子类实现父类的方法
class Person():
    def __init__(self,name):
        self.name=name
    def get_name(self):
        return self.name
##  这里将父类所继承的方法进行重写
class Man(Person):
    def get_name(self):
        return "Man"

xm=Person("xiao ming")
print(xm.get_name())            ## xiao ming

xm=Man("xiao ming")
print(xm.get_name())            ## Man




## demo3 针对父类属性进行初始化
class Person():
    def __init__(self,name):
        self.name=name
    def get_name(self):
        return self.name
class Man(Person):
    ## 针对父类属性进行初始化
    def __init__(self,name,sex):
        Person.__init__(self,name)
        self.sex=sex
    def get_name(self):
        return "Man"

xm=Person("xiao ming")
print(xm.get_name())            ## xiao ming

xm=Man("xiao ming",'boy')
print(xm.name+xm.sex)            ## Man




## demo4   子类继承了父类同样拥有父类所包含的方法
class Car():
    def exclaim(self):
        print("I'm am car!!!!")
class Tesla(Car):
    pass
give_me_a_car=Car()
give_me_a_car.exclaim()
give_me_a_Tesla=Tesla()      
give_me_a_Tesla.exclaim()       ## 子类继承了父类同样拥有父类所包含的方法




##demo5    父类覆盖了父类原有的方法
class Car():
    def exclaim(self):
        print("I'm am car!!!!")
class Tesla(Car):        ## 父类完成了子类的初始化
    def exclaim(self):
        print("I'm tesla!!")
give_me_a_car=Car()
give_me_a_car.exclaim()
give_me_a_Tesla=Tesla()
give_me_a_Tesla.exclaim()



## 基于父类多种子类方法
class Person():
    def __init__(self,name):
        self.name=name

class MDPerson(Person):
    def __init__(self,name):
        self.name="Docker"+name

class JDPerson(Person):
    def __init__(self,name):
        self.name =name+",Esquire"

person=Person('fudd')
doctor=MDPerson('fudd')
lawyer=JDPerson('fudd')
print(person.name)
print(doctor.name)
print(lawyer.name)




##demo6    实现构造方法的多构建
class car():
    def exlaim(self):
        print("I'm a car!!!!")
class Tesla():
    def exlaim(self):
        print('I am a tesla')
    def need_a_push(self):
        print('A little help here?')

give_me_a_car=car()
give_me_a_car.exlaim()
give_me_a_tesala=Tesla()
give_me_a_tesala.need_a_push()

super调用

使用super方法可以让子类调用父类的方法

python 复制代码
class Person:
    def __init__(self,name):
        self.name=name

class EmailPetrson(Person):
    def __init__(self,name,email):
        super().__init__(name)      ## 子类调用父类方法,父类的方法已经被子类所引用
        self.email=email

bob=EmailPetrson('bob','bob@163.com')
print(bob.name,bob.email)

对getter和setter属性进行隐藏(封装)

python 复制代码
class Duck():
    def __init__(self,input_name):
        self.hide_name=input_name
    def get_name(self):
        print('inside getter')
        return self.hide_name
    def set_name(self,input_name):
        print('insider setter')
        self.hide_name=input_name
    name=property(get_name,set_name)        ## 通过字段将getter和setter内容进行隐藏
fowl=Duck('hallo')

## 同过此特性隐藏了对象中的内容(装饰器)
print(fowl.name)
fowl.name=('hllll')

fowl.set_name('6666')
print(fowl.name)

# ## 通过getter也可调用内部方法
# print(fowl.get_name())
#
# fowl.hide_name='ooookkkkk'
# print(fowl.hide_name)

装饰器的使用

@classmethod和@property使用

python 复制代码
## property装饰器的用法

## demo1
class Duck():
    def __init__(self,input_name):
        self.hide_name=input_name
    @property
    def name(self):                 ## 函数名发生修改
        print('inside getter')
        return self.hide_name
    @name.setter
    def name(self,input_name):      ## 函数名发生修改
        print('insider setter')
        self.hide_name=input_name
    # name=property(get_name,set_name)        ## 通过字段将getter和setter内容进行隐藏
fowl=Duck('hallo')

## 同过此特性隐藏了对象中的内容
print(fowl.name)
fowl.name=('hllll')
print(fowl.name)



## demo2
class Circle():
    def __init__(self,radius):
        self.radius = radius
    @property
    def diameter(self):
        return 2*self.radius

c=Circle(5)
print(c.diameter)   ## 10
c.radius=7
print(c.diameter)   ## 14



## demo3
class Duck():
    def __init__(self, input_name):
        self.__name = input_name
    @property
    def name(self):
        print('inside the getter')
        return self.__name
    @name.setter
    def name(self,input_name):
        print('inside the setter')
        self.__name = input_name

fowl=Duck('hallo')
print(fowl.name)
fowl.name='Hooc'
print(fowl.name)



## demo4    @classmethod

class A():
    ## 这里的count是类全局的变量
    count=0
    def __init__(self):
        A.count+=1
    def exclaim(self):
        print('I am an A!!!')
    @classmethod
    def kids(cls):
        print('A has',cls.count)
num_A=A()
buzzsy_A=A()
whezzy_a=A()
A.kids()

@staticmethod使用

定义之后的方法不需要传递参数(self,cls)

python 复制代码
### staticmethod
class A:
    @staticmethod
    def a():
        print('I AM GOOD')
A=A.a()


## instance method,class method,static method

class A:
    count=0
    def __init__(self):
        A. count+=1
    def exclaim(self):
        print('I AM an A')
    @classmethod
    def kids(cls):
        print('A has',cls.count)
    @staticmethod
    def a():
        print('我是A')

a=A()

## 类方法
A.kids()
A.exclaim()

## 实例化方法
a.kids()
a.exclaim()

多态练习使用

python 复制代码
## 鸭子类型

class Quote():
    def __init__(self,person,words):
        self.person = person
        self.words = words
    def who(self):
        return self.person
    def says(self):
        return self.words+'.'

class QuestionQuote(Quote):
    def says(self):
        return self.words+'?'

class ExclamationQuote(Quote):
    def says(self):
        return self.words+'!'

class BabblingBrook():
    def who(self):
        return 'Brook'
    def says(self):
        return 'Babble'
brook=BabblingBrook()
def who_says(obj):
    print(obj.who(),'says',obj.says())

who_says(brook)

hunter=Quote('Elmer Fudd',"I'm a good day")
# print(hunter.who(),'says:',hunter.says())
#
hunter1=QuestionQuote('Bus Bunny',"what's up,doc")

who_says(hunter1)
# print(hunter1.who(),'says:',hunter1.says())
hunter2=ExclamationQuote('Daffy Ducks',"it's rabbit season")

who_says(hunter2)
# print(hunter2.who(),'says:',hunter2.says())

常见的魔术方法使用

python 复制代码
class world:
    def __init__(self,text):
        self.text=text
    def equals(self,word2):
        return self.text.lower()==word2.text.lower()

first=world('hai')
second=world('HAI')
third=world('llo')
print(first.equals(second))     ## True
print(second.equals(third))     ## False



class word():
    def __init__(self,text):
        self.text=text
    def __eq__(self, word2):
        return self.text.lower()==word2.text.lower()

first=word('ha')        ##  True
second=word('HA')       ##  False
third=word('LO')

常见的魔术方法(见如下魔术方法)

python 复制代码
class word():
    def __init__(self,text):
        self.text=text
    def __eq__(self, word2):
        return self.text.lower()==word2.text.lower()
    def __str__(self):
        return self.text
    def __repr__(self):
        return 'Word('+self.text+')'

first=word('ha')     ### first结果是word(ha)
print(first)         ###  ha 

对象的组合使用

python 复制代码
### 类与类之间不存在继承关系,而是彼此互相组合在一起
class Tail():
    def __init__(self,length):
        self.length = length

class Bill():
    def __init__(self,description):
        self.description =description

class Duck():
    def __init__(self,bill,tail):
        self.bill = bill
        self.tail = tail
    def about(self):
        print('The duck has a',self.bill.description,'bill and a',self.tail.length,'tail')

tail=Tail('long')
bill=Bill('orange')
duck=Duck(bill,tail)
duck.about()            ##  The duck has a orange bill and a long tail

五、综合练习

python 复制代码
验证一个文本里面的密码,如果正确返回,不正确重试3次,添加注册(用户名和密码)登录流程
密码文件使用pickle标准库保存
python 复制代码
import pickle
import getpass
## 读取文件内容
def open_database():
    try:
        with open('passwd.pkl', 'rb') as f:
            return pickle.load(f)
    except IOError as error:
        return False
    except Exception as e:
        raise  False

## 更新文本内容
def update_database(user_data):
    try:
        with open('passwd.pkl','wb') as f:
            pickle.dump(user_data,f)
            return True
    except IOError as error:
        return False
    except Exception as e:
        raise  False


## 注册
def register():
    ## 输入用户名和密码
    username=input('请输入用户名:')
    ## {"username":"passwd"}
    user_data=open_database() if open_database() else {}
    if username in user_data.keys():
        print('用户已经存在')
        return False
    userpasswd=input("请输入密码:")
    user_data[username]=userpasswd
    db_status=update_database(user_data)
    if not db_status:
        print('注册失败!')
    print('注册成功')


## 登录
def login():
    count=0
    username = input('请输入用户名:')
    while count<3:
        userpasswd=input("请输入密码:")
        # userpasswd = getpass.getpass("请输入密码:")    ## 隐藏密码
        user_data=open_database()
        passwd=user_data.get(username)
        if passwd is None:
            print('用户不存在!')
            break
        if userpasswd!=passwd:
            count+=1
            print('密码错误!,请重试,最多3次')
            continue
        print('密码正确!')
        break
    else:
        print('已经重试了3次,退出!')



## 入口
def main():
    while True:
        user_choice=input("1.注册  2.登录   0.退出")
        if user_choice=="1":
            register()
        elif user_choice=="2":
            login()
        else:
            break

if __name__ == '__main__':
    main()
相关推荐
WillaWang2 小时前
Liquid:在assign定义变量时使用allow_false
前端
蔗理苦2 小时前
2025-10-06 Python不基础 15——metaclass
python·metaclass
GISer_Jing2 小时前
得物前端二面潜在问题详解
前端·javascript·面试
带娃的IT创业者2 小时前
Function Call实战效果:准确率提升86%背后的数据与思考,兼谈MCP的未来
人工智能·python·function call·性能分析·技术趋势·mcp·roi
qianmo20212 小时前
乐理知识学习内容
学习
可触的未来,发芽的智生3 小时前
触摸未来2025.10.05:悟神经网络符号之伤,拥抱声音的宇宙
人工智能·python·神经网络·算法·架构
飞天巨兽3 小时前
HTTP基础教程详解
前端·网络·网络协议·http
_bong3 小时前
python评估算法性能
数据结构·python·算法
儒雅芝士3 小时前
BIT*算法
python