当我们使用足够的python的面向对象概念进行编程时,我们需要创建对象并访问其属性。这些对象通常是从一个类创建的,而getattr函数可以帮助我们访问该对象的属性。
在下面的示例中,我们从一个名为Best Buy的类中创建一个对象,并将值分配给该对象的属性。然后,在下面显示的打印语句中访问这些贡品。
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