【python 语法】内置方法

2024-01-15 00:00:00

目录:

getattr

getattr(object, attribute, default) 用于获取对象的属性值,如果属性不存在可以返回默认值。

class Car:
    def __init__(self, brand, color):
        self.brand = brand
        self.color = color
        self.speed = 0
    
    def start_engine(self):
        return "引擎启动"
    
    def stop_engine(self):
        return "引擎关闭"

car = Car("Toyota", "红色")

# 获取存在的属性
print(getattr(car, 'brand'))      # 输出:Toyota
print(getattr(car, 'color'))      # 输出:红色

# 获取不存在的属性(会报错)
# print(getattr(car, 'price'))    # AttributeError!

# 使用默认值避免报错
print(getattr(car, 'price', '暂无价格'))  # 输出:暂无价格
print(getattr(car, 'weight', 1500))      # 输出:1500

# 获取方法并调用
engine_method = getattr(car, 'start_engine')
print(engine_method())            # 输出:引擎启动

# 直接调用方法
print(getattr(car, 'stop_engine')())  # 输出:引擎关闭

如果要获取字典的属性,可以使用 get() 方法。

p = { 'name': 'dkvirus' }

# print(getattr(p, 'name')) # 报错: AttributeError: 'dict' object has no attribute 'name'
print(p['name']) # 'dkvirus'
print(p.get('name')) # 'dkvirus'
print(p.get('age')) # None
print(p.get('age', 18)) # 没有 age 属性,使用默认值 18

hasattr

hasattr(object, attribute) 检查类的实例对象是否具有指定属性和方法。

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def say_hello(self):
        return f"Hello, I'm {self.name}"

# 创建实例
person = Person("小明", 25)

# 检查属性是否存在
print(hasattr(person, 'name'))     # 输出:True
print(hasattr(person, 'age'))      # 输出:True
print(hasattr(person, 'gender'))   # 输出:False

# 检查方法是否存在
print(hasattr(person, 'say_hello')) # 输出:True
print(hasattr(person, 'run'))      # 输出:False

如果要判断字典是否具有指定属性,使用 in 操作符。


p = { 'name': 'dkvirus' }

print(hasattr(p, 'name')) # False
print('name' in p) # True

返回首页

本文总阅读量  次
皖ICP备17026209号-3
总访问量: 
总访客量: