Why is my object not printing


#1

Hi,

I was working on the Python Exercise on Inheritance and Polymorphism , Dunder II.
I wrote the below code as an experiment :slight_smile:

class Atom:
  def __init__(self, label):
    self.label = label
    
  def __add__(self,other):
    return Molecule([self,other])
    
class Molecule:
  def __init__(self, atoms):
    if type(atoms) is list:
	    self.atoms = atoms
      
sodium = Atom("Na")
print(sodium.label)  #Output : Na
chlorine = Atom("Cl")
print(chlorine.label) #Output : Cl
#salt = Molecule([sodium, chlorine])
salt = sodium + chlorine
print(salt.atoms) #Output : [<__main__.Atom object at 0x7f5e77d037b8>, <__main__.Atom object at 0x7f5e77d037f0>]

I am not understanding why print is not working with salt.atoms since it is a list which is a built-in data type and print should work on it perfectly.
Why is it returning the type and address of the objects in the list instead of the contents of the list ?


#2

Because the default representation is not of much use, you could use __str__ or __repr__ to solve this problem:

https://stackoverflow.com/questions/1436703/difference-between-str-and-repr


#3

Thanks, I did think so as well.
But if that is true, why is
print(sodium.label) working ?
label is variable which gets printed, similarly atoms is a list so should print not work directly ?
why does print(sodium.label) not return the address of the label variable but return the address for print(salt.atoms)


#4

because this prints a instance variable.

the list is printed, you can see the [] of the list. The list however contains the default representation of the instances, which isn’t very nice.