MFB
MFB

Reputation: 19797

Python Class property not taking arguments properly

This Class should accept an argument to the Keys property, but when I try MyUserInstance.Keys('foo'), it doesn't work. Instead it says TypeError: Keys() takes exactly 2 arguments (1 given). How is it wrong?

# User
class User:
    def __init__(self,
            Username = 'New User',
            **kwargs):
        self.Username = Username
        self.__dict__.update(kwargs)

    @property
    def Keys(self,collection):
        try:
            return {k:1 for k in db.UserPreferences.find_one({
                'Type':'VisibleKeys',
                'UserID':self._id,
                'CollectionName':collection})['Keys']}
        except:
            return None

    def __repr__(self):
        return '<User: "%s">' % self.Username

Upvotes: 0

Views: 690

Answers (1)

jdi
jdi

Reputation: 92569

Keys is a bound property of an instance of your class. That means you must first have an instance.

user = User()
user.Keys = "foo"

Also get rid of the collection arg. Thats a getter. You can only define the arg on setters.

It looks like it really should be just a method. So actually, get rid of the property decorator and use: user.keys("foo")

You can read about how to define getter, setter, and deleter here: http://docs.python.org/library/functions.html#property

Also python convention would normally reserve the uppercase for class names. It would be User.keys

Upvotes: 5

Related Questions