以下是更多的Python关键字及简要示例:
21、 class
- 定义类,用于面向对象编程(OOP):
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass # 子类需要重写此方法
class Dog(Animal):
def speak(self):
return "Woof!"
my_dog = Dog("Rufus")
print(my_dog.speak()) # 输出: Woof!
22、 global
- 在函数内部声明全局变量:
count = 0
def increment():
global count
count += 1
return count
increment()
print(count) # 输出: 1
23、 nonlocal
- 在嵌套函数中引用外层函数的局部变量:
def outer():
counter = 0
def inner():
nonlocal counter
counter += 1
return counter
return inner
inc_func = outer()
print(inc_func()) # 输出: 1
print(inc_func()) # 输出: 2
24、 try-except-finally
- 异常处理结构:
try:
risky_operation()
except ValueError:
print("A ValueError occurred!")
except Exception as e:
print(f"An error occurred: {e}")
finally:
clean_up_resources()
25、 lambda
- 创建匿名函数(也称作“lambda表达式”):
add = lambda x, y: x + y
result = add(3, 5)
print(result) # 输出: 8
26、 pass
- 空语句,占位符,无任何操作:
def do_nothing():
pass
27、 del
- 删除变量、属性或元素:
my_list = [1, 2, 3]
del my_list[1] # 删除第二个元素
print(my_list) # 输出: [1, 3]
28、 isinstance()
- 检查对象是否属于某种类型(或其子类):
obj = 42
if isinstance(obj, int):
print("It's an integer!")
当前文章价值7.4元,扫一扫支付后添加微信提供帮助!(如不能解决您的问题,可以申请退款)
评论已关闭!