Python Forum
List of Objects print <__main. Problem
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List of Objects print <__main. Problem
#1
Hello,

i am starting to learn python. For a better understanding i want to implement a genetic Algorithm. But acutally i am having troubles with my code.
So i create an instance of the class Chromosom and LKW and add them to the list polulation.
Then i want to print population, but i can only see:
"<__main__.Chromosom object at 7asd711yx2d"

What can i do to see the real numbers of population? +


Greetings Kol789



class Chromosom(object):                          #Chromosom wird erstellt mit Fitness,Index, Chromosom  
  
  def __init__(self, fitness, index, chromosom):
    self.fitness=fitness
    self.index=index
    self.chromosom= chromosom
    
  def myfunc(self):                               # Printe ein Chromosom
    print(self.fitness,self.index,self.chromosom )

  def __str__(self):
    return "<Test a:%s b:%s c:%s>" % (self.fitness, self.index, self.chromosom)


class LKW(object):                                # Erzeuge LKW mit Uhrzeit

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

  def __str__(self):
    return "<Test a:%s>" % (self.uhrzeit)

population=[]
 
p1= Chromosom(1,5,[123456])
print(p1)

p2=LKW(12)
print(p2)


population.append(p1)
population.append(p2)

print(population)
Reply
#2
you need to define __repr__() method.
when you print the list it uses __repr__() method of the object
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
At first i would like to thank you for your fast answer :)

But as mentioned i am sadly beginner so i have some question:

Instead of __str__ method i need to define a __repr__()right?
The str method needs to be written in the class LKW and Chromosom?
And if so, how should the method look like? My guess would be:

def__repr__(Self)
return repr(self.fitness, self.index, self.chromosom)

or do i need to implement a method __repr__ for population?

Once again thank you for your help
Reply
#4
you need to implement __repr__ for your class(es)
the idea of __repr__ is to be unambiguous, __str__ - to be readable.
Generally you should always define __repr__ and define __str__ if you need to - i.e. if there is no __str__, __repr__ will be used instead.

check https://stackoverflow.com/questions/1436...r-and-repr
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
Hello buran,

i made the __repr__method for my class chromosom und LKW. Here is an example:

def __repr__(self, fitness, index, chromosom):
return "<a:%s, b:%s, c:%s, d:%s>" % (self.fitness, self.index, self.chromosom)


How can i now see the list population? Do i need to write sth. like print(repr(population)?

Thank you. I am thankfulfor your help
Reply
#6
just print population
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
Hello buran,

this is acutally my code:

class Chromosom(object):                          #Chromosom wird erstellt mit Fitness,Index, Chromosom  
   
  def __init__(self, fitness, index, chromosom):
    self.fitness=fitness
    self.index=index
    self.chromosom= chromosom
     
  def myfunc(self):                               # Printe ein Chromosom
    print(self.fitness,self.index,self.chromosom )
 
  def __repr__(self, fitness, index, chromosom):
    return "<a:%s, b:%s, c:%s, d:%s>" % (self.fitness, self.index, self.chromosom)
 
class LKW(object):                                # Erzeuge LKW mit Uhrzeit
 
  def __init__(self, uhrzeit):
    self.uhrzeit=uhrzeit
 
  def __str__(self):
    return "<Test a:%s>" % (self.uhrzeit)
 
population=[]
  
p1= Chromosom(1,5,[123456])
print(p1)
 
p2=LKW(12)
print(p2)
 
 
population.append(p1)
population.append(p2)
 
print(population)
But when i print the population i get an error __repr__ missing 3 required positional arguments in line 25 print(p1)
What am i doing wrong?
Reply
#8
First of all - start using BBcode when post code, errors, output.

You don't need other argument than self in __repr__

e.g. line 11:
def __repr__(self):
note - you will need __repr__ also for LKW class
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#9
To clarify: print without formatting print the return value of the __str__ method of an object.
If the method __str__ does not exist, __repr__ is used instead. __str__ and __repr__ could be independent. If even __repr__ does not exist, the __repr__ method is made automatically.
This is why you get always this output with a virtual memory address of the object.
Often the __repr__ method is used to output a str, which could be evaluated back to a new object.


class Representation:
    def __repr__(self):
        return "__repr__"


class StrRepresentation:
    def __str__(self):
        return "__str__"


class Both:
    def __str__(self):
        return "__str__"

    def __repr__(self):
        return "__repr__"



representation = Representation()
str_representation = StrRepresentation()
both = Both()



print("representation:", representation)
print("str_representation:", str_representation)
print("both:", both)
Output:
representation: __repr__ str_representation: __str__ both: __str__
As a shortcut, you can assign the __str__ method to the __repr__ method.

class BothSame:
    def __str__(self):
        return "__str__"

    __repr__ = __str__
The class returns the same values for __str__ and __repr__.

If you want to print some object, you could define with the format method or f-strings which you want to have.


class Both:
    def __str__(self):
        return "__str__"

    def __repr__(self):
        return "__repr__"

both = Both()
print(both) # print the __str__
print(repr(both)) # print the __repr__

print("{!s} {!r}".format(both, both)) # print __str__ and __repr__
print(f"{both!s} {both!r}")
Output:
__str__ __repr__ __str__ __repr__ __str__ __repr__
Your first class a bit improved:
class Chromosom(object):
    """
    Docstrings are useful
    """

    def __init__(self, fitness, index, chromosom):
        """
        fitness := ?
        index := ?
        chromosom := ?
        """
        self.fitness = fitness
        self.index = index
        self.chromosom = chromosom

    def myfunc(self):
        """
        Return current data
        """
        return self.fitness, self.index, self.chromosom

    def __str__(self):
        """
        It's used if str() was called with this instance or print uses it also by default
        """
        return f"<Test a:{self.fitness} b:{self.index} c:{self.chromosom}>"

    def __repr__(self):
        """
        Return a representation as string.
        """
        return f"{self.__class__.__name__}({self.fitness}, {self.index}, {self.chromosom})"


chromosom = Chromosom(1,2,3)

print(chromosom)
print(repr(chromosom))
Output:
<Test a:1 b:2 c:3> Chromosom(1, 2, 3)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#10
the OP problem is that when inside a container, when print the container, the __repr__ of each element is used.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Problem with print formatting using definitions Tberr86 2 2,011 Mar-20-2021, 06:23 PM
Last Post: DPaul
  How to print all iterations of min and max for a 2D list alaina 4 2,915 Nov-11-2020, 05:53 AM
Last Post: alaina
  Why does this function print empty list? hhydration 1 1,538 Oct-28-2020, 02:03 AM
Last Post: deanhystad
  How can I print the number of unique elements in a list? AnOddGirl 5 3,286 Mar-24-2020, 05:47 AM
Last Post: AnOddGirl
  Highscore problem, need to print top 5 Camiosobro123 1 1,571 Jan-27-2020, 10:43 PM
Last Post: Camiosobro123
  sorting a deck of cards (objects in a list) itmustbebunnies 1 7,202 Dec-05-2018, 02:44 AM
Last Post: ichabod801
  another positional argument error (...and executing objects stored in a list) itmustbebunnies 7 4,210 Nov-16-2018, 07:18 PM
Last Post: itmustbebunnies
  Print The Length Of The Longest Run in a User Input List Ashman111 3 3,207 Oct-26-2018, 06:56 PM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020