简体   繁体   English

如何让 object 正确显示?

[英]How do I get the object to correctly display?

I am trying to display some information about an object, including the name, but instead, it is displaying a weird string.我试图显示有关 object 的一些信息,包括名称,但它显示的是一个奇怪的字符串。 I am pretty new to python, and I have just started working with classes.我是 python 的新手,我刚刚开始使用课程。

This is the code I wrote:这是我写的代码:

class Test:
    def __init__(name,item):
        name.item = item
    def display(name):
        print(f"Name: {name}\nItem: {name.item}")
testname = Test("test")
testname.display()

And I got:我得到了:

Name: <__main__.Test object at 0x7f76f0733f10>
Item: test

instead of:代替:

Name: testname
Item: test

So what's happening here is you are printing the object itself, or the instance of the class. The 0x7f76f0733f10 is the memory address where that object lives if I recall correctly.所以这里发生的是你正在打印 object 本身,或者 class 的实例。如果我没记错的话,0x7f76f0733f10 是 memory 地址,object 所在的地址。

Apart from that, it would be better if you used "self" because it is a convention.除此之外,如果您使用“self”会更好,因为这是约定俗成的。 You need to use the __str__ method in order to give your class a proper name.你需要使用__str__方法来给你的 class 一个合适的名字。

def __str__(name):
    return "testcode"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM