r/AskProgramming • • Apr 25 '26

Python Python Descriptors

class A:
	def __set_name__(self, owner, value):
		self.value = value

	def __get__(self, obj, type=None):
		return obj.__dict__.get(self.value)
	
	def __set__(self, obj, value):
		if value < 9:
			raise ValueError("no")
		obj.__dict__[self.value] = value
	
class B:
	a = A()

obj = B()
obj.a = 38
print(obj.a)

obj2 = B()
print(obj2.a)

I am Learning Descriptors In Python,

My 1st question Is how can I set a default value to attribute a In class B ? I have found a way but that doesn't look familiar :

a = A() if not A() else 87

My next confusion Is about __set_name__ , what it does and why to Implement It?

Another Question Is, does a = A() create class attribute or Instance attribute? It looks like a class attribute but it's an Instance attribute, Right?

0 Upvotes

10 comments sorted by

View all comments

Show parent comment

1

u/One-Type-2842 Apr 26 '26

I have Read your shared python docs on Descriptors, byt I don't found what obj_type=None does in __get__() method explain this..

1

u/Temporary_Pie2733 Apr 26 '26 edited Apr 27 '26

obj_type is, among other things, how you distinguish accessing the descriptor from the class that owns it and an instance of that class. Given

b = B()

b.a is equivalent to B.__dict__['a'].__get__(b, B), while B.a is equivalent to B.__dict__['a'].__get__(B, None). The same method is called in both cases, just with different arguments.

It's also worth reading https://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/ for an in-depth explanation of how attribute lookup works in Python.