python怎么获取对象的属性值

52次阅读
没有评论

共计 539 个字符,预计需要花费 2 分钟才能阅读完成。

要获取对象的属性值,可以使用点操作符或 getattr() 函数。

  1. 点操作符:使用点操作符可以直接获取对象的属性值。
class MyClass:
def __init__(self, x):
self.x = x
obj = MyClass(10)
print(obj.x)  # 输出:10
  1. getattr() 函数:getattr() 函数通过属性名字符串来获取对象的属性值。
class MyClass:
def __init__(self, x):
self.x = x
obj = MyClass(10)
print(getattr(obj, 'x'))  # 输出:10

如果对象的属性不存在,可以使用 getattr() 函数的第三个参数来指定默认值。

class MyClass:
def __init__(self, x):
self.x = x
obj = MyClass(10)
print(getattr(obj, 'y', 0))  # 输出:0

使用 getattr() 函数还可以在运行时动态获取对象的属性值。

class MyClass:
def __init__(self, x):
self.x = x
obj = MyClass(10)
attr_name = input("请输入属性名:")
print(getattr(obj, attr_name))

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-21发表,共计539字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)