新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
python如何打印對象的屬性值
在Python中,可以使用dir()函數(shù)和getattr()函數(shù)來打印對象的屬性值。dir()函數(shù)可以列出對象的所有屬性和方法,getattr()函數(shù)可以根據(jù)屬性名獲取屬性值。

以下是一個簡單的示例:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
創(chuàng)建一個Person對象
person = Person("張三", 30)
使用dir()函數(shù)列出對象的所有屬性和方法
attributes = dir(person)
使用單元表格打印屬性名和屬性值
print("屬性名t屬性值")
for attribute in attributes:
if not attribute.startswith("__"): # 過濾掉內置屬性和方法
value = getattr(person, attribute)
print(f"{attribute}t{value}")
輸出結果:
屬性名 屬性值 age 30 name 張三 say_hello>
在這個示例中,我們定義了一個Person類,然后創(chuàng)建了一個Person對象,接著,我們使用dir()函數(shù)列出對象的所有屬性和方法,然后使用getattr()函數(shù)獲取每個屬性的值,并使用單元表格打印出來,注意,我們過濾掉了以雙下劃線開頭的內置屬性和方法。
當前文章:python如何打印對象的屬性值
文章位置:http://www.5511xx.com/article/djeipog.html


咨詢
建站咨詢
