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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T22:17:58+00:00 2026-05-30T22:17:58+00:00

How to add functions to a class dynamically based on some criteria. For ex

  • 0

How to add functions to a class dynamically based on some criteria.

For ex i have a class as follwos:

class A(object):
     def __init__(self,type):
         self.type = type

Now based on the ‘type’ value i want to add functions from either class B or class C to the class A.

For ex.

lass B(object):
    def fun1(self):
        print 'fun1'
    def fun2(self):
        print 'fun2'

class C(object):
    def fun3(self):
        print 'fun3'
    def fun4(self):
        print 'fun4'

If ‘type’ attribute value of class A is ‘B’ then dynamically add functions of class B (i.e. fun1 and fun2) to class A or else if ‘type’ attribute value is ‘C’ then add functions of class C to class A (i.e. fun3 and fun4) to class A, such that at further in my code i can access those functions as A.fun1() or A.fun3.

I am guessing that metaprograming might hekp me in this but i dont have a clue as to how to do it. Please guide.

Further i have to create objects of class A and be able to use these functions via those objects of class A.

a = class A(type='B')
a.fun1()  #should work

Kindly help as i am not able to figure this out.

This is the part of my code.

class Group(object):
    def __init__(self,type):
        if type == 'source'
            self.mgr = SManager(self)             #grp_mgr
        elif type == 'target'
            self.mgr = TManager(self)

    def __getattr__(self,name):
        if hasattr(self.mgr,name):
            return getattr(self.mgr,name)
        return AttributeError

class SManager(object):
    def __init__(self,groupobj):
        self.some_list = []
        self.groupobj = groupobj

    def doProcess(self):
        #this function accesses self.groupobj
        pass

    def get_valid_list(self):
        #this function accesses self.groupobj
        pass

But with this i am getting the following error.

    if hasattr(self.mgr,name):
  File "c:\workspace\project\dev.py", line 27, in __ge
tattr__
    if hasattr(self.mgr,name):
  File "c:\workspace\project\dev.py", line 27, in __ge
tattr__
    if hasattr(self.mgr,name):
  File "c:\workspace\project\dev.py", line 27, in __ge
tattr__
    if hasattr(self.mgr,name):
  File "c:\workspace\project\dev.py", line 27, in __ge
tattr__
    if hasattr(self.mgr,name):
  File "c:\workspace\project\dev.py", line 27, in __ge
tattr__
    if hasattr(self.mgr,name):
RuntimeError: maximum recursion depth exceeded while calling a Python object

I am not able to figure out as to where i am making a mistake. Before incorporating this i tried this example with a simple snippet which worked but when i did the same in actual code it is throwing error.
Pls help

  • 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-30T22:17:59+00:00Added an answer on May 30, 2026 at 10:17 pm

    As I already told in a question comment: you probably don’t need metaclasses at all.

    But since you’re not giving more information, this is how what you’re asking could be done with metaclasses:

    class MetaX(type):
    
        def __add__(cls, other):
            name = '{}+{}'.format(cls.__name__, other.__name__)
            return type(cls)(name, (cls, other), dict())
    
    
    class X(object):    # metaclass=MetaX in py3k
    
        __metaclass__ = MetaX
    
        def __add__(self, other):
            cls = type(self) + type(other)
            return cls
    

    That’s it, you’ll just need to inherit from X.

    Example:

    class A(X):
        def func_a(self):
            print "I'm in func_a"
    
    class B(X):
        def func_b(self):
            print "I'm in func_b"
    
    class C(X):
        def func_c(self):
            print "I'm in func_c"
    
    L = A + B
    l = L()
    l.func_a()  # -> I'm in func_a
    l.func_b()  # -> I'm in func_b
    
    P = A + C
    p = P()
    p.func_a()  # -> I'm in func_a
    p.func_c()  # -> I'm in func_c
    

    Edit: What you really need depends on how your actual code looks like.

    What you described in your question is a dynamic inheritance, if that’s what you really need, then IMO a metaclass is the right tool and overriding __getattr__ it would be just a hack.

    If you don’t want to build a whole metaclass you could build just use some kind of class factory:

    def get_enhanced_A(typ)   # you can't use type as a keyword here
        dct = {'B': B, 'C': C}
        return type('A+{}'.format(typ), (A,dct[typ]), dict())
    

    I wouldn’t know which one of the two options looks better.

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

Sidebar

Related Questions

I am trying to add some dynamically (based on the URI) created class names
I have a class that I want to dynamically remove based on a link.
Is there a way to add some html based on a certain class name
I have two functions to add and remove table rows that contain a form
I would like to add some debugs for my simple ruby functions and I
I have a series of divs: <div class=some_class active>Some Content</div> <div class=some_class>Different Content</div> <div
I have an RMA form that I've been able to add fields dynamically, but
I have written a script which dynamically creates a html table based off server
We can add any variable to class dynamically in php. What would be the
I have made a form which adds controls dynamically with user selecting the type

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.