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

  • Home
  • SEARCH
  • 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 3808386
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T15:08:23+00:00 2026-05-19T15:08:23+00:00

I don’t know if this will make sense, but… I’m trying to dynamically assign

  • 0

I don’t know if this will make sense, but…

I’m trying to dynamically assign methods to an object.

#translate this
object.key(value)
#into this
object.method({key:value})

To be more specific in my example, I have an object (which I didn’t write), lets call it motor, which has some generic methods set, status and a few others. Some take a dictionary as an argument and some take a list. To change the motor’s speed, and see the result, I use:

motor.set({'move_at':10})
print motor.status('velocity')

The motor object, then formats this request into a JSON-RPC string, and sends it to an IO daemon. The python motor object doesn’t care what the arguments are, it just handles JSON formatting and sockets. The strings move_at and velocity are just two of what might be hundreds of valid arguments.

What I’d like to do is the following instead:

motor.move_at(10)
print motor.velocity()

I’d like to do it in a generic way since I have so many different arguments I can pass. What I don’t want to do is this:

# create a new function for every possible argument
def move_at(self,x)
    return self.set({'move_at':x})
def velocity(self)
    return self.status('velocity')
#and a hundred more...

I did some searching on this which suggested the solution lies with lambdas and meta programming, two subjects I haven’t been able to get my head around.

UPDATE:

Based on the code from user470379 I’ve come up with the following…

# This is what I have now....
class Motor(object):
    def set(self,a_dict):
        print "Setting a value", a_dict
    def status(self,a_list):
        print "requesting the status of", a_list
        return 10

# Now to extend it....
class MyMotor(Motor):
    def __getattr__(self,name):
        def special_fn(*value):
            # What we return depends on how many arguments there are.
            if len(value) == 0: return self.status((name))
            if len(value) == 1: return self.set({name:value[0]})
        return special_fn
    def __setattr__(self,attr,value): # This is based on some other answers
        self.set({attr:value})


x = MyMotor()
x.move_at = 20 # Uses __setattr__
x.move_at(10)  # May remove this style from __getattr__ to simplify code.
print x.velocity()

output:

Setting a value {'move_at': 20}
Setting a value {'move_at': 10}
10

Thank you to everyone who helped!

  • 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-05-19T15:08:24+00:00Added an answer on May 19, 2026 at 3:08 pm

    What about creating your own __getattr__ for the class that returns a function created on the fly? IIRC, there’s some tricky cases to watch out for between __getattr__ and __getattribute__ that I don’t recall off the top of my head, I’m sure someone will post a comment to remind me:

    def __getattr__(self, name):
        def set_fn(self, value):
            return self.set({name:value})
        return set_fn
    

    Then what should happen is that calling an attribute that doesn’t exist (ie: move_at) will call the __getattr__ function and create a new function that will be returned (set_fn above). The name variable of that function will be bound to the name parameter passed into __getattr__ ("move_at" in this case). Then that new function will be called with the arguments you passed (10 in this case).

    Edit

    A more concise version using lambdas (untested):

    def __getattr__(self, name):
        return lambda value: self.set({name:value})
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I don't know if anyone has seen this issue before but I'm just stumped.
I don't expect a straightforward silver bullet answer to this, but what are the
Don't need to do this right now but thinking about the future... What would
I don't know Regex very well, and I'm trying to get all of the
I don't know if thats right but for some reason my stored procedure is
I don't know if this is possible. I display a table of results and
I don't know if i am doing it right, this is what I got:
I don't think this should be in my view, but instead handled by the
I don't know when to add to a dataset a tableadapter or a query
I don't understand where the extra bits are coming from in this article about

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.