Getter and installer control for python class

Consider the following class:

class Token:
    def __init__(self):
        self.d_dict = {}

    def __setattr__(self, s_name, value):
        self.d_dict[s_name] = value

    def __getattr__(self, s_name):
        if s_name in self.d_dict.keys():
            return self.d_dict[s_name]
        else:
            raise AttributeError('No attribute {0} found !'.format(s_name))

There is another function in my Token code (e.g. get_all () that returns d_dict has (s_name) that tell me if my token has a specific attribute).

In any case, I think this is a flaw in my plan, because it does not work: when I create a new instance, the python tries to call __setattr__('d_dict', '{}').

How can I achieve similar behavior (perhaps in a more pythonic way?) Without having to write something like Token.set (name, value) and get (name), each of which I want to set or get an attribute for the token.

Critics about the lack of design and / or stupidity are welcome :)

Thanks!

+5
source share
6 answers

d_dict.

, , , , , __dict__, . , ?

.

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x
+3

__dict__ :

def __init__(self):
    self.__dict__['d_dict'] = {}

.

+3

, , __init__. __new__ d_dict __init__. , , , , .

>>> class  Foo(object):
...     def __new__(cls, *args):
...             my_cls = super(Foo, cls).__new__(cls, *args)
...             my_cls.d_dict = {}
...             return my_cls

>>> f = Foo()
>>> id(f.d_dict)
3077948796L
>>> d = Foo()
>>> id(d.d_dict)
3078142804L

, , hackish: __new__ , d_dict static, , "", , .

+2

, pythonic, . , d_dict.

class Token(object):

    def __init__(self):
        super(Token,self).__setattr__('d_dict', {})

    def __getattr__(self,name):
        return self.a[name]

    def __setattr__(self,name,value):
        self.a[name] = value

.

+1

, __getattr__ , , __setattr__ .

+1

I think we can say something about the overall design of your class if you explain its purpose. For example,

# This is a class that serves as a dictionary but also has user-defined methods
class mydict(dict): pass

# This is a class that allows setting x.attr = value or getting x.attr:
class mysetget: pass

# This is a class that allows setting x.attr = value or getting x.attr:
class mygetsethas: 
    def has(self, key):
        return key in self.__dict__

x = mygetsethas()
x.a = 5
print(x.has('a'), x.a)

I think the last class is closest to what you had in mind, and I also like to play with the syntax and get a lot of joy from it, but unfortunately this is not good. The reasons why it is impractical to use the attributes of objects to reuse the dictionary: you cannot use x.3, you are conflicting with x.has(), you need to put quotation marks in has('a')and many others.

0
source

All Articles