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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T10:53:14+00:00 2026-05-30T10:53:14+00:00

I’m defining several classes intended to be used for multiple inheritance, e.g.: class A:

  • 0

I’m defining several classes intended to be used for multiple inheritance, e.g.:

class A:
    def __init__(self, bacon = None, **kwargs):
        self.bacon = bacon
        if bacon is None:
            self.bacon = 100
        super().__init__(**kwargs)
class Bacon(A):
    def __init__(self, **kwargs):
        """Optional: bacon"""
        super().__init__(**kwargs)

class Eggs(A):
    def __init__(self, **kwargs):
        """Optional: bacon"""
        super().__init__(**kwargs)


class Spam(Eggs, Bacon):
    def __init__(self, **kwargs):
        """Optional: bacon"""
        super().__init__(**kwargs)

However, I have multiple classes (e.g. possibly Bacon, A, and Spam, but not Eggs) that care about when their property bacon is changed. They don’t need to modify the value, only to know what the new value is, like an event. Because of the Multiple Inheritance nature I have set up, this would mean having to notify the super class about the change (if it cares).

I know that it might be possible if I pass the class name to the method decorator, or if I use a class decorator. I don’t want to have all the direct self-class referencing, having to create lots of decorators above each class, or forcing the methods to be the same name, as none of these sound very pythonic.

I was hoping to get syntax that looks something like this:

    @on_change(bacon)
    def on_bacon_change(self, bacon):
        # read from old/new bacon
        make_eggs(how_much = bacon)

I don’t care about the previous value of bacon, so that bacon argument isn’t necessary, if this is called after bacon is set.

  • Is it possible to check if a super class has a method with this
    decorator?

  • If this isn’t feasible, are there alternatives to passing events like
    this, up through the multiple-inheritance chain?

EDIT:

The actual calling of the function in Spam would be done in A, by using a @property and @bacon.setter, as that would be the upper-most class that initializes bacon. Once it knows what function to call on self, the problem only lies in propagating the call up the MI chain.

EDIT 2:

If I override the attribute with a @bacon.setter, Would it be possible to determine whether the super() class has a setter for bacon?

  • 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-30T10:53:15+00:00Added an answer on May 30, 2026 at 10:53 am

    What you call for would probably be nicely fit with a more complete framework of signals, and so on – maybe even invite for Aspected Oriented Programing.

    Without going deep into it however, a metaclass and a decorator can do just what you are asking for – I came up with these, I hope they work for you.

    If you’d like to evolve this in to something robust and usable, write me – if nothing like this exists out there, it wouldbe worth to keep an utility package in pipy for this.

    def setattr_wrapper(cls):
        def watcher_setattr(self, attr, val):
            super(cls, self).__setattr__(attr, val)
            watched = cls.__dict__["_watched_attrs"]
            if attr in watched:
                for method in watched[attr]:
                    getattr(self, method)(attr, val)
        return watcher_setattr
    
    class AttrNotifier(type):
        def __new__(metacls, name, bases, dct):
            dct["_watched_attrs"] = {}
            for key, value in dct.items():
                if hasattr(value, "_watched_attrs"):
                    for attr in getattr(value, "_watched_attrs"):
                        if not attr in dct["_watched_attrs"]:
                            dct["_watched_attrs"][attr] = set()
                        dct["_watched_attrs"][attr].add(key)
            cls = type.__new__(metacls, name, bases, dct)
            cls.__setattr__ = setattr_wrapper(cls)
            return cls
    
    
    def on_change(*args):
        def decorator(meth):
            our_args = args
            #ensure that this decorator is stackable
            if hasattr(meth, "_watched_attrs"):
                our_args = getattr(meth, "_watched_attrs") + our_args
            setattr(meth, "_watched_attrs", our_args)
            return meth
        return decorator
    
    # from here on, example of use:
    class A(metaclass=AttrNotifier):
        @on_change("bacon")
        def bacon_changed(self, attr, val):
            print ("%s changed in %s to %s" % (attr, self.__class__.__name__, val)) 
    
    
    class Spam(A):
        @on_change("bacon", "pepper")
        def changed(self, attr, val):
            print ("%s changed in %s to %s" % (attr, self.__class__.__name__, val)) 
    
    a = A()
    a.bacon = 5
    
    b = Spam()
    b.pepper = 10
    b.bacon = 20
    

    (tested in Python 3.2 and Python 2.6 – changing the declaration of the “A” class for
    Python 2 metaclass syntax)

    edit – some words on what is being done
    Here is what happens:
    The metaclass picks all methods marked with the “on_close” decorator, and register then in a dictionary on the class – this dictionary is named _watched_attrs and it can be accessed as a normal class attribute.

    The other thing the metaclass does is to override the __setattr__ method for the clas once it is created. This new __setattr__ just sets the attribute, and then checks the _wacthed_attrs dictionary if there are any methods on that class registered to be called when the attribute just changed has been modified – if so, it calls it.

    The extra indirection level around watcher_setattr (which is the function that becomes each class’s __setattr__ is there so that you can register different attributes to be watched on each class on the inheritance chain – all the classess have indepently acessible _watched_attrs dictionaries. If it was not for this, only the most specilized class on the inheritance chain _watched_attrs would be respected.

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

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I used javascript for loading a picture on my website depending on which small
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I am doing a simple coin flipping experiment for class that involves flipping a
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
I would like to count the length of a string with PHP. The string
For some reason, after submitting a string like this Jack’s Spindle from a text

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.