Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8555445
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T15:07:28+00:00 2026-06-11T15:07:28+00:00

In python, I can alter the state of an instance by directly assigning to

  • 0

In python, I can alter the state of an instance by directly assigning to attributes, or by making method calls which alter the state of the attributes:

foo.thing = 'baz'

or:

foo.thing('baz')

Is there a nice way to create a class which would accept both of the above forms which scales to large numbers of attributes that behave this way? (Shortly, I’ll show an example of an implementation that I don’t particularly like.) If you’re thinking that this is a stupid API, let me know, but perhaps a more concrete example is in order. Say I have a Document class. Document could have an attribute title. However, title may want to have some state as well (font,fontsize,justification,…), but the average user might be happy enough just setting the title to a string and being done with it …

One way to accomplish this would be to:

class Title(object):
     def __init__(self,text,font='times',size=12):
         self.text = text
         self.font = font
         self.size = size
     def __call__(self,*text,**kwargs):
         if(text):
             self.text = text[0]
         for k,v in kwargs.items():
             setattr(self,k,v)
     def __str__(self):
         return '<title font={font}, size={size}>{text}</title>'.format(text=self.text,size=self.size,font=self.font)

class Document(object):
     _special_attr = set(['title'])
     def __setattr__(self,k,v):
         if k in self._special_attr and hasattr(self,k):
             getattr(self,k)(v)
         else:
             object.__setattr__(self,k,v)

     def __init__(self,text="",title=""):
         self.title = Title(title)
         self.text = text

     def __str__(self):
         return str(self.title)+'<body>'+self.text+'</body>'

Now I can use this as follows:

doc = Document()
doc.title = "Hello World"
print (str(doc))
doc.title("Goodbye World",font="Helvetica")
print (str(doc))

This implementation seems a little messy though (with __special_attr). Maybe that’s because this is a messed up API. I’m not sure. Is there a better way to do this? Or did I leave the beaten path a little too far on this one?

I realize I could use @property for this as well, but that wouldn’t scale well at all if I had more than just one attribute which is to behave this way — I’d need to write a getter and setter for each, yuck.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T15:07:29+00:00Added an answer on June 11, 2026 at 3:07 pm

    It is a bit harder than the previous answers assume.

    Any value stored in the descriptor will be shared between all instances, so it is not the right place to store per-instance data.
    Also, obj.attrib(...) is performed in two steps:

    tmp = obj.attrib
    tmp(...)
    

    Python doesn’t know in advance that the second step will follow, so you always have to return something that is callable and has a reference to its parent object.

    In the following example that reference is implied in the set argument:

    class CallableString(str):
        def __new__(class_, set, value):
            inst = str.__new__(class_, value)
            inst._set = set
            return inst
        def __call__(self, value):
            self._set(value)
    
    class A(object):
        def __init__(self):
            self._attrib = "foo"
        def get_attrib(self):
            return CallableString(self.set_attrib, self._attrib)
        def set_attrib(self, value):
            try:
                value = value._value
            except AttributeError:
                pass
            self._attrib = value
        attrib = property(get_attrib, set_attrib)
    
    a = A()
    print a.attrib
    a.attrib = "bar"
    print a.attrib
    a.attrib("baz")
    print a.attrib
    

    In short: what you want cannot be done transparently. You’ll write better Python code if you don’t insist hacking around this limitation

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In Python I can use the iterkeys() method to iterate over the keys of
In Python I can use get method to get value from an dictionary without
After I installed MySQLdb by sudo apt-get install python-mysqldb I can import and use
I know python can be run on GAE what is different erlang and python
I'm planning to use very big numbers in Python, but wonder if Python can
In python we can use multiprocessing modules. If there is a similar library in
In Python you can do a: from a import b as c How would
In Python I can define a function as follows: def func(kw1=None,kw2=None,**kwargs): ... In this
In python how can i develop this algorithm to find common patterns in a
Very new to python and can't understand why this isn't working. I have a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.