字典, 可爱的字典
接下来我要教你另外一种让你伤脑筋的容器型数据结构,因为一旦你学会这种容器,你将拥有超酷的能力。这是最有用的容器:字典(dictionary)。
Python 将这种数据类型叫做 “dict”,有的语言里它的名称是 “hash”。这两种名字我都会用到,不过这并不重要,重要的是它们和列表的区别。你看,针对列表你可以做这样的事情:
>>> things = ['a', 'b', 'c', 'd']
>>> print things[1]
b
>>> things[1] = 'z'
>>> print things[1]
z
>>> print things
['a', 'z', 'c', 'd']
>>>
你可以使用数字作为列表的索引,也就是你可以通过数字找到列表中的元素。而 dict 所作的,是让你可以通过任何东西找到元素,不只是数字。是的,字典可以将一个物件和另外一个东西关联,不管它们
的类型是什么,我们来看看:
>>> stuff = {'name': 'Zed', 'age': 36, 'height': 6*12+2}
>>> print stuff['name']
Zed
>>> print stuff['age']
36
>>> print stuff['height']
74
>>> stuff['city'] = "San Francisco"
>>> print stuff['city']
San Francisco
>>>
在这里我使用了两个数字。其实我可以使用任何东西,不过这么说并不准确,不过你先这么理解就行了。
当然了,一个只能放东西进去的字典是没啥意思的,所以我们还要有删除物件的方法,也就是使用 del
这个关键字:
>>> del stuff['city']
>>> del stuff[1]
>>> del stuff[2]
>>> stuff
{'name': 'Zed', 'age': 36, 'height': 74}
>>>
class Song(object):
#在class的定义中,有一些强制性的规定,
#在命名的时候,首字母必须是要大写,并且在这个类名之后要跟一个冒号
#在定义的时候可以对class的类属性进行声明,基本的语法格式如下:
def __init__(self,lyrics): #添加属性
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print(line)
happy_bday = Song(["Happy birthday to you",
"I don't want to get sued",
"So I'll stopu right there"])
bulls_on_parade = Song(["They rally aroud the family",
"with pockets full of shells"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
#运行结果
Happy birthday to you
I don't want to get sued
So I'll stopu right there
They rally aroud the family
with pockets full of shells
Class的使用
class School: #class 后跟的内容首字母大写
def __init__(self,country,city): #定义school的属性,分别是所在的国家和城市
self.country = country
self.city = city
def my(self): #实例方法
print("My school is located in %s, %s " % (self.city,self.country))
a = School('China','beijng') #给School幅值
print(a.country)
print(a.city)
b = a.my() #调用实例方法,括号内为空,并赋值给b
print(b) #打印b
China
beijng
My school is located in beijng, China
运行结果多出一行None
python 输出后面多一个None_运行结果最后多出来一个none-CSDN博客
是这个函数没有返回值,默认返回None
class MyClass:
def my_function(self):
pass # 这个函数没有返回值,默认返回None
# 实例化对象
obj = MyClass()
result = obj.my_function()
print(result) # 输出 None
怎么修改呢?
class Company:
def __init__(self,name,city):
self.name = name
self.city = city
def C(abc):
print(f"公司名称为{abc.name},所在地为{abc.city}")
a = Company('LOVE','BJ')
a.C() #函数里包含了打印,直接运行即可,就不会出现None
#如果B=a.C() print(B) 就会多出一行None
#函数里包含了打印,直接运行即可,就不会出现None #如果B=a.C() print(B) 就会多出一行None
python运行脚本时出none怎么回事_mob64ca12ee66e3的技术博客_51CTO博客
参考:
[Python-5]Python面向对象_[<__main__.student_information object at 0x0000029-CSDN博客