Questions about the use of descriptors.


Steven W. Orr

Question 1:

I have a class A with one attribute and I define __get__ and __set__ for that
class. Then I create another class B that uses it.

Why does B require that the instance of A be a class variable in B and not
created as an instance variable in __init__?

# This works fine.
class Truth(object):
def __init__(self):
self.is_slave = False

def __get__(self, obj, objtype):
return self.is_slave

def __set__(self, obj, val):
if not self.is_slave and val:
self.is_slave = val

class TruthHolder(object):
IsSlave = Truth()

def set_truth(self):
self.IsSlave = True

tt = TruthHolder()
print tt.IsSlave
tt.IsSlave = True
print tt.IsSlave
tt.IsSlave = False
print tt.IsSlave

But if I change TruthHolder to not start as a class variable

class TruthHolder(object):
def __init__(self):
self.IsSlave = Truth()

def set_truth(self):
self.IsSlave = True

it doesn't seem to use descriptor methods of Truth. It's just using the
default setter and getter of TruthHolder.


Is it the case that people only use descriptors for classes with single
attributes? Or is it more frequent that descriptors are used with classes that
have multiple attributes?

I feel like this is powerful juju, but I'm not getting when I should be using
property and when I should be using descriptors.

General note: I see really simple examples in my searches, but I'd like to see
a good practical example that has just a bit more meat on it.

Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Latest member

Latest Threads