开发者

python 2.7 __init__ behavior on self

开发者 https://www.devze.com 2023-01-24 04:58 出处:网络
I have a python question that I\'m sure is pretty simple - please feel free to disabuse me of any sort of bad practice while you\'re at it. I have the following code:

I have a python question that I'm sure is pretty simple - please feel free to disabuse me of any sort of bad practice while you're at it. I have the following code:

class User(dict,BaseDBI):
    def __init__(self,uid=None,username=None):
        self['uid']=str(uuid())     
        if uid == None and username is not None:            
            uid_struct = self.Get('data/username.kch',username)         
            if uid_struct is not None:
                self = self.Get('data/user.kch',uid_struct['uid'])

As you can tell this User is simply an extended dict object. It also accesses a few simple Get and Set methods on a couple of Kyoto Cabinet db files. I put in some print statements to trace through what's going on and everything is being set properly, but when I create a User object (e.g.):

user = User(username='someusername')

and then print user I only hav开发者_如何学JAVAe a new dict object that has the brand new uid generated by the first line under __init__

Thanks for any wisdom!


python variables are references. when you assign to self, you are replacing that reference but not altering the object which is returned by __init__.

The easiest thing may be to simply use the dict.update method to copy all key/value pairs into self. This should 'just work' since you're already inheriting from dict.

Inheritance is only appropriate for a relationship like A is a B. You indicate that a User is a dict, that's fine, but I doubt that a User is a BaseDBI. It's more likely that you want a User to have a database, in which case composition is more appropriate. This probably seems nit-picky, but will prevent you from making bizarre and obscene systems.


You need to call the inherited constructors. Something like:

def __init__(self,uid=None,username=None):
    dict.__init__(self)
    BaseDBI.__init__(self)

Also assigning to self will just replace the value in the local variable self. It will not have any effect on the object.


If you need to return an already existing instance or your class, you need to define a __new__ method

By the time __init__ is called, a fresh instance has already been created

0

精彩评论

暂无评论...
验证码 换一张
取 消