# Dictionaries & Python方法
# Python 字典是无序的项目集合。它以一组键:值对的形式包含数据。
# 访问和写入数据
my_dictionary = {"song": "Estranged", "artist": "Guns N' Roses"}
print(my_dictionary["song"]) #Estranged
my_dictionary["song"] = "Paradise City" #赋值运算符 (=)
print(my_dictionary["song"]) #Paradise City
# 字典
roaster = {"q1": "Ashley", "q2": "Dolly"}
print(roaster) #{'q1': 'Ashley', 'q2': 'Dolly'}
# .update() 合并字典
dict1 = {'color': 'blue', 'shape': 'circle'}
dict2 = {'color': 'red', 'number': 42}
dict1.update(dict2)
print(dict1) #{'color': 'red', 'shape': 'circle', 'number': 42}
# 字典中的值为任意类型 - 字符串、整数、列表、其他字典、布尔值等等,键必须始终是不可变的数据类型,例如字符串、数字或元组
dictionary = {
1: 'hello',
'two': True,
'3': [1, 2, 3],
'Four': {'fun': 'addition'},
5.0: 5.5
}
# 键值对
# .keys()通过对象返回键dict_keys。
# .values()通过对象返回值dict_values。
# .items()通过对象返回键和值dict_items。
ex_dict = {"a":"Monday","b":"Tuesday","c":"Friday"}
print(ex_dict.keys()) #dict_keys(['a', 'b', 'c'])
print(ex_dict.values()) #dict_values(['Monday', 'Tuesday', 'Friday'])
print(ex_dict.items()) #dict_items([('a', 'Monday'), ('b', 'Tuesday'), ('c', 'Friday')])
# get方法 访问某个dictionary值(如果该值存在)
name = {"name":"Victor"} .get("name")
print(name) #Vivtor
nickname = {"name": "Victor"}.get("nickname")
print(nickname) #None
nickname_with_default = {"name": "Victor"}.get("nickname","昵称不是一个正确的健")
print(nickname_with_default) #昵称不是一个正确的健
# .pop()方法 删除键值对
famous_museums = {'Washington': 'Smithsonian Institution', 'Paris': 'Le Louvre', 'Athens': 'The Acropolis Museum'}
famous_museums.pop('Athens')
print(famous_museums) #{'Washington': 'Smithsonian Institution', 'Paris': 'Le Louvre'}
# Python__repr__()方法 告诉 Python该类的字符串表示形式应该是什么,只能有一个参数,self并且应该返回一个字符串。
class Employee:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
john = Employee('John')
print(john) # John
# 类方法 第一个参数通常称为self
class Dog:
# 类的方法
def bark(self):
print("Ham-Ham")
# 创建新实例
charlie = Dog()
# 调用方法
charlie.bark()
# 类在使用之前需要实例化
class Car:
"This is an empty class"
pass
# 实例化
ferrari = Car()
# 打印对象的信息
print(f"Created a car instance: {ferrari}") #Created a car instance: <__main__.Car object at 0x7f8d4e3c2f70>
# 类变量 类变量可以通过instance.variable或class_name.variable语法来访问
class my_class:
class_variable = "I am a Class 变量!"
x = my_class()
y = my_class()
print(x.class_variable)
print(y.class_variable)
# .__init__() 方法 初始化新创建的对象
class Animal:
def __init__(self, voice):
self.voice = voice
# 当创建一个类实例时,实例变量
# 创建“voice”并将其设置为输入值。
cat = Animal('喵喵')
print(cat.voice) # Meow
dog = Animal('Woof')
print(dog.voice) # Woof
# type()函数 返回传递给它的参数的数据类型
a = 1
print(type(a)) #<class 'int'>
a = 1.1
print(type(a)) #<class 'float'>
a = 'b'
print(type(a)) #<class 'str'>
a = None
print(type(a)) #<class 'NoneType'>
# 定义类
class Animal:
def __init__(self, name, number_of_legs):
self.name = name
self.number_of_legs = number_of_legs
print(f"Created an animal named {self.name} with {self.number_of_legs} legs.")
# 创建一个 Animal 实例
dog = Animal("Dog", 4)
print(dir(dog))
# dir()函数 内置dir()函数不带任何参数,返回当前范围内所有属性的列表
class Employee:
def __init__(self, name):
self.name = name
def print_name(self):
print("Hi, I'm " + self.name)
print(dir())
print(dir(Employee))
# __main__ 特殊的变量名 引用当前文件上下文的标识符 指示某个 Python 文件或模块是否是被直接执行的脚本
# script.py
def main():
print("This script is being run directly.")
if __name__ == "__main__":
main()
__main__
详解
在 Python 中,__main__
是一个特殊的变量名,用作标识当前文件上下文的标识符。它用于指示某个 Python 文件或模块是否是被直接执行的脚本。了解 __main__
的作用对于编写可重用和模块化的代码非常重要。以下是关于 __main__
的详细解释:
__name__
变量
每个 Python 模块都有一个 __name__
属性。当一个模块被直接运行时,__name__
的值被设置为 "__main__"
。如果模块是被另一个模块导入的,那么 __name__
的值就是该模块的文件名(不包含路径和扩展名)。
使用 __name__ == "__main__"
这个条件通常用于决定模块中的某些代码块是否应该在模块被直接执行时运行。以下是一个常见的用法:
# script.py
def main():
print("This script is being run directly.")
if __name__ == "__main__":
main()
在上面的代码中,main()
函数只有在 script.py
被直接执行时才会被调用。如果 script.py
被作为模块导入,那么 main()
函数不会被执行,因为 __name__
不会等于 "__main__"
。
例子
假设有两个文件:script.py
和 another_script.py
。
script.py:
def main():
print("Running script.py directly")
if __name__ == "__main__":
main()
another_script.py:
import script
print("another_script.py is running")
如果你直接运行 script.py
:
$ python script.py
输出将是:
Running script.py directly
如果你运行 another_script.py
:
$ python another_script.py
输出将是:
another_script.py is running
在这种情况下,script.py
中的 main()
函数不会被执行,因为 script.py
是作为模块被导入的。
结论
使用 if __name__ == "__main__":
结构可以让你的 Python 文件既可以作为独立的脚本运行,也可以作为模块被其他文件导入而不执行某些段落的代码。这是一种常见的设计模式,尤其是在编写多功能和可重用的代码时。