Questions about the use of descriptors.

Discussion in 'Python' started by Steven W. Orr, Mar 15, 2012.

  1. 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__?

    E.g.,
    # 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.

    Question2:

    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 syslang.net
     
    Steven W. Orr, Mar 15, 2012
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Gordon Beaton

    Re: Running out of file descriptors

    Gordon Beaton, Jul 24, 2003, in forum: Java
    Replies:
    0
    Views:
    398
    Gordon Beaton
    Jul 24, 2003
  2. Oz Levanon

    File Descriptors Leak

    Oz Levanon, Nov 25, 2003, in forum: Java
    Replies:
    3
    Views:
    586
    Robert Olofsson
    Nov 25, 2003
  3. SmokingGun
    Replies:
    0
    Views:
    802
    SmokingGun
    Feb 9, 2004
  4. rooban
    Replies:
    0
    Views:
    606
    rooban
    Jul 21, 2004
  5. Replies:
    0
    Views:
    372
Loading...

Share This Page