python getattr函数_在python中对self使用getattr函数
发布日期:2021-08-20 00:17:05 浏览次数:15 分类:技术文章

本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:java 音量_java – 音量为零?
下一篇:php 和mysql连接测试代码_php中mysql连接和基本操作代码(快速测试使用,简单方便)_php实例...

发表评论

最新留言

关注你微信了!
[***.104.42.241]2025年01月17日 05时56分29秒