本文共 682 字,大约阅读时间需要 2 分钟。
首先,对类使用大写字母,对变量使用小写字母,因为其他Python程序员更容易阅读:)
现在,您不需要在类本身中使用getattr()
只要做:self.attribute
然而,一个例子是:class Foo(object): # Class Foo inherits from 'object'
def __init__(self, a, b): # This is the initialize function. Add all arguments here
self.a = a # Setting attributes
self.b = b
def func(self):
print('Hello World!' + str(self.a) + str(self.b))
>>> new_object = Foo(a=1, b=2) # Creating a new 'Foo' object called 'new_object'
>>> getattr(new_object, 'a') # Getting the 'a' attribute from 'new_object'
1
但是,更简单的方法是直接引用属性>>> new_object.a
1
>>> new_object.func()
Hello World!12
或者,通过使用getattr():>>> getattr(new_object, 'func')()
Hello World!12
尽管我解释了getattr()函数,
我似乎不明白你想达到什么目的,请发布一个示例输出。
转载地址:https://blog.csdn.net/weixin_31649177/article/details/114362366 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!