定义class类,想输出其中表达的内容,输出方式有哪几种表达?

class PyLanguage:
name = “Python语言中文网”
add = “http://c.biancheng.net/"
def int(self, name, add):
self.name = name
self.add = add
def out(self):
print(self.name,”的网址为”, self.add)
say = PyLanguage()
say.out()

讨论数量: 1
Jason990420

The __str__() method returns a human-readable, or informal, string representation of an object. This method is called by the built-in print(), str(), and format() functions. If you don’t define a __str__()` method for a class, then the built-in object implementation calls the __repr__() method instead.

The __repr__() method returns a more information-rich, or official, string representation of an object. This method is called by the built-in repr() function. If possible, the string returned should be a valid Python expression that can be used to recreate the object. In all cases, the string should be informative and unambiguous.

In general, the __str__() string is intended for users and the __repr__() string is intended for developers.

class PyLanguage():

    def __init__(self, name, add):
        self.name = name
        self.add = add

    def __str__(self):
        return f"PRINT>> PyLanguage: 'name':'{self.name}', 'add':'{self.add}'."

    def __repr__(self):
        return f"DEBUG>> PyLanguage: 'name':'{self.name}', 'add':'{self.add}'."

name = "Python 语言中文网"
add  = "http://c.biancheng.net/"
say = PyLanguage(name, add)
>>> say
DEBUG>> PyLanguage: 'name':'Python 语言中文网', 'add':'http://c.biancheng.net/'.
>>> print(say)
PRINT>> PyLanguage: 'name':'Python 语言中文网', 'add':'http://c.biancheng.net/'.
6个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!