descriptor

How does Python bypass normal attribute lookup to find `__dict__`?

别来无恙 提交于 2019-12-03 21:59:38
I understand that __dict__ in obj.__dict__ is a descriptor attribute of type(obj) , so the lookup for obj.__dict__ is type(obj).__dict__['__dict__'].__get__(obj) . From https://stackoverflow.com/a/46576009 It's tempting to say that __dict__ has to be a descriptor because implementing it as a __dict__ entry would require you to find the __dict__ before you can find the __dict__ , but Python already bypasses normal attribute lookup to find __dict__ when looking up other attributes , so that's not quite as compelling as it initially sounds. If the descriptors were replaced with a '__dict__' key

How to call methods on Python class descriptor objects?

跟風遠走 提交于 2019-12-03 16:13:42
I created a class String() with __get__() , __set__() , and a method to_db() ; however, when I do name = String() , I can't do self.name.to_db() because it's calling to_db() on the value returned by __get__() , not the object " name ". class String(object): def __init__(self, value=None): if value: self.value = str(value) def __get__(self, instance, owner): return self.value def __set__(self, instance, value): self.value = str(value) def to_db(self): return {'type':'string', 'value': self.value} class Example(object): name = String() age = Integer() def __init__(self,name,age): self.name =

Use cases for property vs. descriptor vs. __getattribute__

試著忘記壹切 提交于 2019-12-03 09:06:44
问题 The question refers to which one is preferable to be used in which use case, not about the technical background. In python, you can control the access of attributes via a property , a descriptor , or magic methods . Which one is most pythonic in which use case? All of them seem to have the same effect (see the examples below). I am looking for an answer like: Property : Should be used in case of … Descriptor : In the case of … it should be used instead of a property. Magic method : Only use

How to create decorator for lazy initialization of a property

旧城冷巷雨未停 提交于 2019-12-03 08:14:50
I want to create a decorator that works like a property, only it calls the decorated function only once, and on subsequent calls always return the result of the first call. An example: def SomeClass(object): @LazilyInitializedProperty def foo(self): print "Now initializing" return 5 >>> x = SomeClass() >>> x.foo Now initializing 5 >>> x.foo 5 My idea was to write a custom decorator for this. So i started, and this is how far I came: class LazilyInitializedProperty(object): def __init__(self, function): self._function = function def __set__(self, obj, value): raise AttributeError("This property

python, __slots__, and “attribute is read-only”

馋奶兔 提交于 2019-12-03 06:57:14
问题 I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows: class MyClass( object ) : m = None # my attribute __slots__ = ( "m" ) # ensure that object has no _m etc a = MyClass() # create one a.m = "?" # here is a PROBLEM But after running this simple code, I get a very strange error: Traceback (most recent call last): File "test.py", line 8, in <module> a.m = "?" AttributeError: 'test'

Use cases for property vs. descriptor vs. __getattribute__

北城以北 提交于 2019-12-03 00:41:53
The question refers to which one is preferable to be used in which use case, not about the technical background. In python, you can control the access of attributes via a property , a descriptor , or magic methods . Which one is most pythonic in which use case? All of them seem to have the same effect (see the examples below). I am looking for an answer like: Property : Should be used in case of … Descriptor : In the case of … it should be used instead of a property. Magic method : Only use if …. Example A use case would be an attribute that might not be able to be set in the __init__ method,

Python descriptor vs property [duplicate]

爷,独闯天下 提交于 2019-12-02 22:30:50
Possible Duplicate: When and why might I assign an instance of a descriptor class to a class attribute in Python rather than use a property? I'm confused as to when to use a property vs a descriptor. I read that a property is a specialized descriptor. Can someone please post how this works? You should read the docs on what descriptors actually are. The Cliff's Notes version: descriptors are a low-level mechanism that lets you hook into an object's attributes being accessed. Properties are a high-level application of this; that is, properties are implemented using descriptors. Or, better yet,

python, __slots__, and “attribute is read-only”

戏子无情 提交于 2019-12-02 20:36:03
I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows: class MyClass( object ) : m = None # my attribute __slots__ = ( "m" ) # ensure that object has no _m etc a = MyClass() # create one a.m = "?" # here is a PROBLEM But after running this simple code, I get a very strange error: Traceback (most recent call last): File "test.py", line 8, in <module> a.m = "?" AttributeError: 'test' object attribute 'm' is read-only Is there any wise programmer who can spare a bit of their time and

Python data descriptor did not work as instance variable? [duplicate]

旧城冷巷雨未停 提交于 2019-12-02 09:12:28
问题 This question already has an answer here : Why is the Descriptor not getting called when defined as instance attribute? (1 answer) Closed last year . As the official demo described here, the following code will print Retrieving var "x" . class RevealAccess(object): """A data descriptor that sets and returns values normally and prints a message logging their access. """ def __init__(self, initval=None, name='var'): self.val = initval self.name = name def __get__(self, obj, objtype): print

Maximum recursion depth error with getattr

亡梦爱人 提交于 2019-12-02 04:13:47
I have this code; class NumberDescriptor(object): def __get__(self, instance, owner): name = (hasattr(self, "name") and self.name) if not name: name = [attr for attr in dir(owner) if getattr(owner,attr) is self][0] self.name = name return getattr(instance, '_' + name) def __set__(self,instance, value): name = (hasattr(self, "name") and self.name) if not name: owner = type(instance) name = [attr for attr in dir(owner) if getattr(owner,attr) is self][0] self.name = name setattr(instance, '_' + name, int(value)) class Insan(object): yas = NumberDescriptor() a = Insan() print a.yas a.yas = "osman"