📜  在对象python中打印项目(1)

📅  最后修改于: 2023-12-03 15:08:01.275000             🧑  作者: Mango

在Python中打印对象内容

有时候我们需要在Python中输出对象的内容,可以通过内置函数print()来实现。但是默认情况下,如果直接打印一个对象,只会输出对象的类型和内存地址,而不是对象的具体内容。例如:

class MyClass:
    pass

obj = MyClass()

print(obj)  # <__main__.MyClass object at 0x7fc3936f13d0>

要想打印对象的具体内容,我们需要实现对象的__str__方法,该方法返回一个字符串,描述对象的内容。例如:

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

obj = MyClass("Lucy", 20)

print(obj)  # My name is Lucy, and I'm 20 years old.

在上面的例子中,我们为自定义的MyClass类实现了__str__方法,该方法返回一个字符串,描述了对象的name和age属性。

除了__str__方法外,Python还提供了__repr__方法,用于返回对象的“官方”字符串表示形式(它应该准确、无歧义并且尽可能详尽)。例如:

class MyClass:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
    def __str__(self):
        return f"My name is {self.name}, and I'm {self.age} years old."
    
    def __repr__(self):
        return f"MyClass(name={self.name}, age={self.age})"

obj = MyClass("Lucy", 20)

print(obj)      # My name is Lucy, and I'm 20 years old.
print(repr(obj)) # MyClass(name=Lucy, age=20)

在上面的例子中,我们为MyClass类同时实现了__str__和__repr__方法,并分别打印了它们的返回结果。注意,__repr__方法返回的字符串应该是一个能够被eval()函数正常运行的表达式。