背景:今天继续学习《python学习手册》第27章《类代码编写基础》,今天着重学习一小段的内容:类vs字典,页码是798-801
字典、元组、类在记录数据时有一定的相似之处,有时可以互相替换使用。
元组和字典:
python
>>> rec = ('Bob', 40.5, ['dev','mgr'])
>>> print(rec[0])
Bob
>>> rec = {}
>>> rec['name'] = 'Bob'
>>> rec['age'] = 40.5
>>> rec['jobs']=['dev','mgr']
>>> print(rec['name'])
Bob
类的第一种用法,直接给类添加变量,相当于存储数据。这个比用字典和元组还方便一些,会少一些符号编码。
python
>>> class rec:pass
>>> rec.name = 'Bob'
>>> rec.jobs = 40.5
>>> rec.jobs = ['dev','mgr']
>>>
>>> print(rec.name)
Bob
类的第二种用法,给实例添加变量,这种方法可以记录多条数据,调用也很方便。
python
>>> class rec:pass
>>> pers1 = rec()
>>> pers1.name ='Bob'
>>> pers1.job = ['dev','mgr']
>>> pers1.age = 40.5
>>>
>>> pers2 = rec()
>>> pers2.name = 'Sue'
>>> pers2.jobs=['dev','cto']
>>>
>>> pers1.name,pers2.name
('Bob', 'Sue')
类的正常用法:
python
>>> class Person:
def __init__(self, name, jobs, age=None):
self.name = name
self.jobs = jobs
self.age = age
>>> class Person:
def __init__(self, name, jobs, age=None):
self.name = name
self.jobs = jobs
self.age = age
def info(self):
return (self.name, self.jobs)
>>> rec1 = Person('Bob',['dev','mgr'], 40.5)
>>> rec2 = Person('Sue',['dev', 'cto'])
>>>
>>> rec1.jobs, rec2.info()
(['dev', 'mgr'], ('Sue', ['dev', 'cto']))
尽管我们也可以把函数存储到字典中,但再也没有比类更加自然和有着良好结构的地方。