Search code examples
pythonlistcallable-object

why does python obj.atribute return adress location and obj.atribute.atribute return the value?


To get the value of an attribute I need to call method.attribute.attribute instead of method.attribute, why is this? Calling method.attribute results in a memory address. How should/can I change my code to make method.attribute work?

Most issues regarding this center around calling print(f) instead of print(f())

class MyList:
    """stores a list and does other stuff eventualy"""
    this_list = []

    def __init__(self, *args):
        for arg in args:
            self.this_list.append(arg)

    def print_list(self):
        """prints the atribute:"description" from the stored objects in the list"""
        for x in range(len(self.this_list)):
            print(MyClassObj(self.this_list[x]).description, sep="\n")

This is the code that is supposed to print the value of the attribute description

class MyClassObj:
    """test object to be stores in the "MyList" object."""

    def __init__(self, description):
        self.description = description

This is the object that contains the attribute I want to get.

class CallList:
    """creates the objects, lists and calls the print method"""
    @staticmethod
    def main():
        test1, test2 = MyClassObj("Test1"), MyClassObj("Test2")
        list1 = MyList(test1, test2)
        list1.print_list()

Main() is called outside the above classes.

The output I get is

<__main__.MyClassObj object at 0x007908F0>
<__main__.MyClassObj object at 0x00790910>

Process finished with exit code 0

If i change line:

print(MyClassObj(self.this_list[x]).description.description, sep="\n")

I get the expected result:

Test1
Test2

Process finished with exit code 0

So the question is why and how should I alter my code?


Solution

  • in print_list self.this_list[x] is already a MyClassObj so MyClassObj(self.this_list[x]) creates a new MyClassObj having a MyClassObj as its description.

    Because there is no way defined to convert a MyClassObj to a string for print Python uses a default conversion showing the memory address.