Python-getattr()方法
当我们使用足够的python的面向对象概念进行编程时,我们需要创建对象并访问其属性。这些对象通常是从一个类创建的,而getattr函数可以帮助我们访问该对象的属性。
示例
在下面的示例中,我们从一个名为BestBuy的类中创建一个对象,并将值分配给该对象的属性。然后,在下面显示的打印语句中访问这些贡品。
import time
# declare class
class bestpy:
name = "pyexperts"
course = "python"
# initialize object
n = bestpy()# use of getattr to print name
getattr_bestpy = time.time()
print("公司名称是:" + getattr(n,'name'))
print("getattr_bestpy time execution is : " + str(time.time() - getattr_bestpy),"\n")
# use of conventional method to print course
conventional_bestpy = time.time()
print("It provides work on " + n.course)
print("conventional_bestpt time execution is:" + str(time.time() - conventional_bestpy))输出结果
运行上面的代码给我们以下结果-
公司名称是:pyexperts getattr_bestpy time execution is : 0.0011477470397949219 It provides work on python conventional_bestpt time execution is: 0.0002818107604980469
热门推荐
2 成都训练狗狗
3 怎么训练小狗狗
4 训练狗狗软件
5 如何训练狗狗拉屎
9 狗狗负重训练
10 狗狗多大可以训练大小便
11 怎么训练狗狗萨摩耶
12 狗狗训练书
13 鞍山狗狗训练
14 训练狗狗用品
15 怎样才能训练狗狗听话
16 狗狗如何训练大小便
17 怎样训练狗狗睡狗窝
18 训练狗狗工具