python getattr函数_在python中对self使用getattr函数

本文介绍了Python中如何定义和使用类及属性,并演示了通过getattr()函数与直接访问两种方式来获取类实例的属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,对类使用大写字母,对变量使用小写字母,因为其他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()函数,

我似乎不明白你想达到什么目的,请发布一个示例输出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值