Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Class __init__ Not Working

This is some really simple code I am using with sqlalchemy and I am missing something basic here about how classes work.

class Game(Base):
    __tablename__ = "games"

    id = Column(Integer, primary_key=True)
    a_name = Column(String)

    def __init__(self, **kwargs):
        for k, v in kwargs.iteritems():
             setattr(self, k, v)
        print 'hi'
        self.away_dictionary =  {'name': self.a_name}

    @hybrid_property
    def stuff(self):
        return self.away_dictionary

The following query works:

session.query(Game).first().a_name

but the following query returns an error:

session.query(Game).first().stuff
'Game' object has no attribute 'away_dictionary'

I also have an even more basic problem, when I query the Game class it doesn't print out 'hi'. So could someone please explain why 'hi' isn't printed out everytime I use a Game instance? And the second question is how can I build and access the away_dictionary I want to have for each instance of this class?

like image 909
appleLover Avatar asked Nov 24 '22 20:11

appleLover


1 Answers

You're not creating a Game instance in your queries above, you only pass the Game class object. Hence the init() constructor is never called. If you need a Game instance for query, you need this: session.query(Game()).first().stuff.

like image 98
Frank Ruben Avatar answered Nov 26 '22 11:11

Frank Ruben