Python中類的物件列印


物件是面嚮物件語言 (OOPs) 的一部分,它是類的例項。類是藍圖或模板,它指定給定類的屬性和方法。當我們建立類的物件時,它包含所有與該特定物件相關的例項方法和變數。

使用__str__方法

Python中有兩種方法,即__str__或__repr__,它們會自動呼叫字串並用於列印物件及其詳細資訊。以下是使用__str__方法的語法。

def __str__(self):
	return string_representation
print(object_name(inputs)

def __repr__(self):
	return string_representation
print(object_name(inputs)

示例

在下面的示例中,我們使用Python建立一個類和一個物件;在類中,我們將定義函式以及__str__方法,並在其中提供格式化文字,最後列印物件。

class Person:
   def __init__(self, name, age, gender):
      self.name = name
      self.age = age
      self.gender = gender
        
   def __str__(self):
      return f"My name is {self.name} and I am {self.age} years old."

person1 = Person("John", 30, "male")
person2 = Person("Jane", 25, "female")

print(person1) 
print(person2)

輸出

My name is John and I am 30 years old.
My name is Jane and I am 25 years old.

示例

在下面的示例中,如果我們省略方法的提及,則將列印物件的描述而不是物件的資料。

class Person:
   def __init__(self, language, state, gender):
      self.name = language
      self.age = state
      self.gender = gender
        
person1 = Person("John", 30, "male")
person2 = Person("Jane", 25, "female")

print(person1) 
print(person2)

輸出

<__main__.Person object at 0x0000029D0DAD7250>
<__main__.Person object at 0x0000029D0DBEF7F0>

示例

在Python中,我們還有另一個名為__repr__的方法來列印物件的詳細資訊。此方法與__str__方法相同,但區別在於它處理物件的更多詳細資訊。

class Person:
   def __init__(self, name, state, place):
      self.name = name
      self.state = state
      self.place = place
   def __repr__(self):
      return f"{self.name} belongs to {self.state} and the home town of {self.name} is {self.place}"
        
person1 = Person("John", "Andhra Pradesh", "male")
person2 = Person("Jane", "Telangana", "female")

print(person1) 
print(person2)

輸出

John belongs to Andhra Pradesh and the home town of John is Vishakhapatnam
Jane belongs to Telangana and the home town of Jane is Hyderabad

示例

當我們在使用者定義的類中不使用__repr__並嘗試列印物件時,print語句的輸出將是物件的描述。

class Person:
   def __init__(self, name, state, gender):
      self.name = name
      self.state = state
      self.gender = gender

person1 = Person("John", "Andhra Pradesh", "male")
person2 = Person("Jane", "Telangana", "female")

print(person1) 
print(person2)

輸出

<__main__.Person object at 0x0000029D0DBE7790>
<__main__.Person object at 0x0000029D0DBE7CA0>

更新於: 2023年11月6日

2K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.