0

I am trying to display some information about an object, including the name, but instead, it is displaying a weird string. I am pretty new to python, and I have just started working with classes.

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
JR2712543
  • 1
  • 2
  • Does this answer your question? [What is the difference between \_\_str\_\_ and \_\_repr\_\_?](https://stackoverflow.com/questions/1436703/what-is-the-difference-between-str-and-repr) – mousetail Dec 06 '22 at 18:34
  • 1
    Why didn't you name the first argument `self` as is the convention? You are making everything much more confusing for yourself. `name` is not a name, but a instance of `Test` – mousetail Dec 06 '22 at 18:34
  • Where do you think your code would come up with the `str` value `'testcode`? You don't supply it anywhere, and nothing in your class constructs the name from anything. – chepner Dec 06 '22 at 18:40
  • @chepner the string 'testcode' was not what I meant to put there, I meant to say 'testname' – JR2712543 Dec 06 '22 at 18:47
  • `testname` is not the name of the object; it's the name of *one* variable that refers to the object. The object itself knows nothing about it. – chepner Dec 06 '22 at 18:48
  • Imagine `a = b = Test("test")`. What name do think the object would have? – chepner Dec 06 '22 at 18:49

2 Answers2

0

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.

0

Apart from that, it would be better if you used "self" because it is a convention. You need to use the __str__ method in order to give your class a proper name.

def __str__(name):
    return "testcode"