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 8932045
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T09:15:10+00:00 2026-06-15T09:15:10+00:00

I am trying to add a new class to an existing class at run

  • 0

I am trying to add a new class to an existing class at run
time (using “type(…)”). I am also trying to override that
new class’ __getattr__ so that I can do my own behavior on
attributes that are not in the new class. For example,
I have class foo, I add class “tool” and I want foo.tool.test
to do something of my own. The code below works but only partly. If I explicitly call __getattr__, it works (see first print)
but when I reference foo.tool.test, my overridden __getattr__ does not get called and an attrbute error is raised.

Your help is greatly appreciated.

class Foo(object):
    def __init__(self):
        self.NameList=[]
        # add new class to ourself
        self.tool = type('tool', (object,), {} )
        # override new class' __getattr__ with call to ourself
        setattr(self.tool, "__getattr__", self.__getattr__ )
        # add one well known test name for now
        self.NameList.append( "test" )

    # should be called by our newly added "tool" object but is only called sometimes...
    def __getattr__(self, attr):
        # print( "__getattr__: %s" % attr )
        if( attr in self.NameList ):     
            return( 99 )
        raise AttributeError("--%r object has no attribute %r" % (type(self).__name__, attr))       

foo = Foo()
# access tool class attribute "test" - it should be seen by the override __getattr__
# the following works...
print( "foo.tool.__getattr__=%d" % foo.tool.__getattr__("test") )  
# but the following does not - why is this not the same as the line above???
print( "foo.tool.test=%d" % foo.tool.test )                         
  • 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-15T09:15:11+00:00Added an answer on June 15, 2026 at 9:15 am

    Python looks for special methods like __getattr__ in an instance’s bases
    __dict__s, not in the instance’s __dict__.

    self.tool is a class. self.tool.test, therefore, will call the __getattr__ of self.tool‘s class (which is object) — this is not what we want to happen.

    Instead, make self.tool an instance, whose class has a __getattr__:

    class Foo(object):
        def __init__(self):
            self.NameList=[]
            # add new class to ourself
            toolcls = type('tool', (object,), { '__getattr__' : self.__getattr__, } )
            self.tool = toolcls()
            self.NameList.append( "test" )
    
        # should be called by our newly added "tool" object but is only called sometimes...
        def __getattr__(self, attr):
            # print("__getattr__: (%s, %s)" % (self.__class__.__name__, attr) )
            if( attr in self.NameList ):     
                return( 99 )
            raise AttributeError("--%r object has no attribute %r" % (
                type(self).__name__, attr)) 
    
    foo = Foo()
    print( "foo.tool.__getattr__=%d" % foo.tool.__getattr__("test") )
    print( "foo.tool.test=%d" % foo.tool.test )    
    

    yields

    foo.tool.__getattr__=99
    foo.tool.test=99
    

    Also, beware that the above code can lead to infinite recursion if an instance of Foo is made without self.NameList being defined. See Ned Batchelder’s post on this suprising pitfall.

    To protect against the possibility of infinite recursion here, use

    def __getattr__(self, attr):
        # print("__getattr__: (%s, %s)" % (self.__class__.__name__, attr) )
        if attr == 'NameList':
            raise AttributeError()
        if( attr in self.NameList ):     
            return( 99 )
        raise AttributeError("--%r object has no attribute %r" % (
            type(self).__name__, attr)) 
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Im trying to add new class to existing project. My class work corectly when
I am trying to add a new class to a pre-existing web application in
I'm trying to add a Metadata partial class to an existing MVC using EF
Im new to asp.net mvc. I'm trying add new model class but it got
I am trying to add a new column into an SQLiteDatabase but every time
In a Scala Compiler Plugin, I'm trying to create a new class that implement
I'm trying to add new object to existing organisational unit in Active Directory. Following
I'm trying to edit an existing .proto file in VS2010 to add a new
I am trying to add three new table to my existing sqlite db and
I am trying to add a new service method to my existing WCF web

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.