0

I'm trying to print these car_object[objectname] objects, but not sure how to do it.... I also have a Cars class. When I do print(car_object[objectname]) I get ObjectmeA160 <__main__.Cars object at 0x027FB970>. what am I doing wrong?

def __iter__(self):
    car_object = {}
    cursor = self._db.execute('SELECT IDENT, MAKE, MODEL, DISPLACEMENT, 
      POWER, LUXURY FROM CARS')
    for row in cursor:
        car_object = {}
        objectname = 'Object'+str(row['IDENT'])
        car_object[objectname] = Cars(ident = row['IDENT'], make = row['MAKE'], 
                  model = row['MODEL'], disp = row['DISPLACEMENT'], power = row['POWER'], luxury = row['LUXURY'])
        print(car_object[objectname])
        yield dict(row)

class Cars:  
    def __init__(self, **kwargs):
        self.variables = kwargs

    def set_Variable(self, k, v):
        self.variables[k] = v

    def get_Variable(self, k):
        return self.variables.get(k, None)
8
  • 4
    That depends entirely on the Cars class. Does it have a .__str__() menthod? Commented Feb 28, 2013 at 21:36
  • @Martijn Pieters added Cars class...how does a __str__() would work in this case? Commented Feb 28, 2013 at 21:39
  • Are you printing anything else before that print() statement? The <__main__.Cars object at 0x027FB970> is for your Cars class, the part in front is not. Commented Feb 28, 2013 at 21:39
  • 1
    And what would you like to print instead? Commented Feb 28, 2013 at 21:40
  • I am printing the objectname I create 'objectname = 'Object'+str(row['IDENT'])' Commented Feb 28, 2013 at 21:41

1 Answer 1

1

The <__main__.Cars object at 0x027FB970> is the standard string for custom objects that do not implement their own .__str__() hook. You can customize it by implementing that method:

class Cars:
    # ....

    def __str__(self):
        return 'Car instance with variables: {!r}'.format(self.variables)
Sign up to request clarification or add additional context in comments.

2 Comments

how do I call this iteratively to print them all? I am getting the input from the db...which has about 30some rows so i want to print them all. do i call from main?
@user2096860: You are doing it correctly to print them all. This hook gives your objects a way to be printed in a different way, so instead of <__main__.Cars object at 0x027FB970> it'll print whatever this method returns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.