How can I break python search: make.up.a.dot.separated.name.and.use.it.until.destroyed = 777

I'm a Python newbie with a very specific itch to experiment with the Python dot-name-lookup process. How to encode a class or function in "make.py" so that these assignment statements execute successfully?

import make

make.a.dot.separated.name = 666
make.something.else.up = 123
make.anything.i.want = 777
+5
source share
1 answer
#!/usr/bin/env python

class Make:
    def __getattr__(self, name):
        self.__dict__[name] = Make()
        return self.__dict__[name]

make = Make()

make.a.dot.separated.name = 666
make.anything.i.want = 777

print make.a.dot.separated.name
print make.anything.i.want

A special method __getattr__is called when the named value is not found. The line make.anything.i.wantended up making the equivalent:

m1 = make.anything    # calls make.__getattr__("anything")
m2 = m1.i             # calls m1.__getattr__("i")
m2.want = 777

__getattr__ Make , . , .

Python - :

object.__getattr__(self, name)

, (.. self). name . () AttributeError.

, , __getattr__() . ( __getattr__() __setattr__().) , __getattr__() . , , ( ). __getattribute__() , .

object.__setattr__(self, name, value)

. (.. ). name - name , value - , .

__setattr__() , self.name = value - . , , self.__dict__[name] = value. , , object.__setattr__(self, name, value).

+15

Source: https://habr.com/ru/post/1720715/


All Articles