📜  Python| getattr() 方法

📅  最后修改于: 2022-05-13 01:54:24.116000             🧑  作者: Mango

Python| getattr() 方法

Python getattr()函数用于访问对象的属性值,并且还提供了在密钥不可用的情况下执行默认值的选项。

getattr() 如何在Python中工作

示例 1:演示 getattr() 的工作原理

Python3
# Python code to demonstrate
# working of getattr()
 
# declaring class
class GfG:
    name = "GeeksforGeeks"
    age = 24
 
# initializing object and
# python getattr() function call
obj = GfG()
 
# use of getattr
print("The name is " + getattr(obj, 'name'))
 
# use of getattr with default
print("Description is " + getattr(obj,
                                  'description',
                                  'CS Portal'))
 
# use of getattr without default
print("Motto is " + getattr(obj, 'motto'))


Python3
# Python code to demonstrate
# working of getattr()
 
# declaring class
class GfG:
    name = "GeeksforGeeks"
    age = 24
 
 
# initializing object
obj = GfG()
 
# use of getattr without default
print("Gender is " + getattr(obj, 'gender'))


Python3
# Python code to demonstrate
# performance analysis of getattr()
import time
 
# declaring class
class GfG:
    name = "GeeksforGeeks"
    age = 24
 
# initializing object
obj = GfG()
 
# use of getattr to print name
start_getattr = time.time()
print("The name is " + getattr(obj, 'name'))
print("Time to execute getattr " + str(time.time() - start_getattr))
 
# use of conventional method to print name
start_obj = time.time()
print("The name is " + obj.name)
print("Time to execute conventional method " + str(time.time() - start_obj))


Python3
# Python code to demonstrate
# working of getattr()
 
# declaring class
class GfG:
    name = "GeeksforGeeks"
    age = 24
 
# initializing object
obj = GfG()
 
# use of getattr without default
print("Motto is " + getattr(obj, 'motto'))


Python3
# Python code to demonstrate
# working of getattr()
 
# declaring class
class GfG:
     
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def call(self, x):
        print(f"{self.name} called with parameters '{x}'")
        return
 
# initializing object
obj = GfG("Vivek", 10)
print(obj)
print(GfG)
print(getattr(obj,'call'))
 
getattr(obj,'call')('arg')


输出:

The name is GeeksforGeeks
Description is CS Portal

例外:

AttributeError: GfG instance has no attribute 'motto'

示例 2:未找到命名属性时的 getattr()

Python3

# Python code to demonstrate
# working of getattr()
 
# declaring class
class GfG:
    name = "GeeksforGeeks"
    age = 24
 
 
# initializing object
obj = GfG()
 
# use of getattr without default
print("Gender is " + getattr(obj, 'gender'))

输出:

AttributeError: 'GfG' object has no attribute 'gender'

示例 3:性能分析和 getattr Python带参数

Python3

# Python code to demonstrate
# performance analysis of getattr()
import time
 
# declaring class
class GfG:
    name = "GeeksforGeeks"
    age = 24
 
# initializing object
obj = GfG()
 
# use of getattr to print name
start_getattr = time.time()
print("The name is " + getattr(obj, 'name'))
print("Time to execute getattr " + str(time.time() - start_getattr))
 
# use of conventional method to print name
start_obj = time.time()
print("The name is " + obj.name)
print("Time to execute conventional method " + str(time.time() - start_obj))

输出:

The name is GeeksforGeeks
Time to execute getattr 5.0067901611328125e-06
The name is GeeksforGeeks
Time to execute conventional method 1.1920928955078125e-06

示例 4:getattr Python默认值

Python3

# Python code to demonstrate
# working of getattr()
 
# declaring class
class GfG:
    name = "GeeksforGeeks"
    age = 24
 
# initializing object
obj = GfG()
 
# use of getattr without default
print("Motto is " + getattr(obj, 'motto'))

输出:

AttributeError: 'GfG' object has no attribute 'motto'

示例 5: Python getattr()函数调用

Python3

# Python code to demonstrate
# working of getattr()
 
# declaring class
class GfG:
     
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def call(self, x):
        print(f"{self.name} called with parameters '{x}'")
        return
 
# initializing object
obj = GfG("Vivek", 10)
print(obj)
print(GfG)
print(getattr(obj,'call'))
 
getattr(obj,'call')('arg')

输出:

<__main__.GfG object at 0x0000023C1ED92748>

>
Vivek called with parameters 'arg'

结果:传统方法比 getattr() 花费的时间更少,但是当必须使用默认值以防缺少属性时,getattr() 是一个不错的选择。

应用: getattr() 有很多应用,其中一些已经在缺少对象属性的情况下被提及,在一些表单属性是可选的 Web 开发中。在机器学习特征集合的情况下也很有用,以防某些特征有时在数据集合中丢失。