Skip to content Skip to sidebar Skip to footer

How To Make A Class Attribute Exclusive To The Super Class

I have a master class for a planet: class Planet: def __init__(self,name): self.name = name (...) def destroy(self): (...) I also have a few clas

Solution 1:

The mixin approach in other answers is nice, and probably better for most cases. But nevertheless, it spoils part of the fun - maybe obliging you to have separate planet-hierarchies - like having to live with two abstract classes each ancestor of "destroyable" and "non-destroyable".

First approach: descriptor decorator

But Python has a powerful mechanism, called the "descriptor protocol", which is used to retrieve any attribute from a class or instance - it is even used to ordinarily retrieve methods from instances - so, it is possible to customize the method retrieval in a way it checks if it "should belong" to that class, and raise attribute error otherwise.

The descriptor protocol mandates that whenever you try to get any attribute from an instance object in Python, Python will check if the attribute exists in that object's class, and if so, if the attribute itself has a method named __get__. If it has, __get__ is called (with the instance and class where it is defined as parameters) - and whatever it returns is the attribute. Python uses this to implement methods: functions in Python 3 have a __get__ method that when called, will return another callable object that, in turn, when called will insert the self parameter in a call to the original function.

So, it is possible to create a class whose __get__ method will decide whether to return a function as a bound method or not depending on the outer class been marked as so - for example, it could check an specific flag non_destrutible. This could be done by using a decorator to wrap the method with this descriptor functionality

classMuteable:
    def__init__(self, flag_attr):
        self.flag_attr = flag_attr

    def__call__(self, func):
        """Called when the decorator is applied"""
        self.func = func
        return self

    def__get__(self, instance, owner):
        if instance andgetattr(instance, self.flag_attr, False):
            raise AttributeError('Objects of type {0} have no {1} method'.format(instance.__class__.__name__, self.func.__name__))
        return self.func.__get__(instance, owner)


classPlanet:
    def__init__(self, name=""):
        pass    @Muteable("undestroyable")defdestroy(self):
        print("Destroyed")


classBorgWorld(Planet):
    undestroyable = True

And on the interactive prompt:

In [110]: Planet().destroy()
Destroyed

In [111]: BorgWorld().destroy()
...
AttributeError: Objects of type BorgWorld have no destroy method

In [112]: BorgWorld().destroy
AttributeError: Objects of type BorgWorld have no destroy method

Perceive that unlike simply overriding the method, this approach raises the error when the attribute is retrieved - and will even make hasattr work:

In [113]: hasattr(BorgWorld(), "destroy")
Out[113]: False

Although, it won't work if one tries to retrieve the method directly from the class, instead of from an instance - in that case the instance parameter to __get__ is set to None, and we can't say from which class it was retrieved - just the owner class, where it was declared.

In [114]: BorgWorld.destroy
Out[114]: <function __main__.Planet.destroy>

Second approach: __delattr__ on the metaclass:

While writting the above, it occurred me that Pythn does have the __delattr__ special method. If the Planet class itself implements __delattr__ and we'd try to delete the destroy method on specifc derived classes, it wuld nt work: __delattr__ gards the attribute deletion of attributes in instances - and if you'd try to del the "destroy" method in an instance, it would fail anyway, since the method is in the class.

However, in Python, the class itself is an instance - of its "metaclass". That is usually type . A proper __delattr__ on the metaclass of "Planet" could make possible the "disinheitance" of the "destroy" method by issuing a `del UndestructiblePlanet.destroy" after class creation.

Again, we use the descriptor protocol to have a proper "deleted method on the subclass":

classDeleted:
    def__init__(self, cls, name):
        self.cls = cls.__name__
        self.name = name
    def__get__(self, instance, owner):
          raise AttributeError("Objects of type '{0}' have no '{1}' method".format(self.cls, self.name))

classDeletable(type):
    def__delattr__(cls, attr):
        print("deleting from", cls)
        setattr(cls, attr, Deleted(cls, attr))


classPlanet(metaclass=Deletable):
    def__init__(self, name=""):
        passdefdestroy(self):
        print("Destroyed")


classBorgWorld(Planet):
    passdel BorgWorld.destroy    

And with this method, even trying to retrieve or check for the method existense on the class itself will work:

In [129]: BorgWorld.destroy
...
AttributeError: Objects of type'BorgWorld' have no 'destroy' method

In [130]: hasattr(BorgWorld, "destroy")
Out[130]: False

metaclass with a custom __prepare__ method.

Since metaclasses allow one to customize the object that contains the class namespace, it is possible to have an object that responds to a del statement within the class body, adding a Deleted descriptor.

For the user (programmer) using this metaclass, it is almost the samething, but for the del statement been allowed into the class body itself:

classDeleted:
    def__init__(self, name):
        self.name = name
    def__get__(self, instance, owner):
          raise AttributeError("No '{0}' method on  class '{1}'".format(self.name, owner.__name__))

classDeletable(type):
    def__prepare__(mcls,arg):

        classD(dict):
            def__delitem__(self, attr):
                self[attr] = Deleted(attr)

        return D()

classPlanet(metaclass=Deletable):
    defdestroy(self):
        print("destroyed")


classBorgPlanet(Planet):
    del destroy

(The 'deleted' descriptor is the correct form to mark a method as 'deleted' - in this method, though, it can't know the class name at class creation time)

As a class decorator:

And given the "deleted" descriptor, one could simply inform the methods to be removed as a class decorator - there is no need for a metaclass in this case:

classDeleted:
    def__init__(self, cls, name):
        self.cls = cls.__name__
        self.name = name
    def__get__(self, instance, owner):
        raise AttributeError("Objects of type '{0}' have no '{1}' method".format(self.cls, self.name))


defmute(*methods):
    defdecorator(cls):
        for method in methods:
            setattr(cls, method, Deleted(cls, method))
        return cls
    return decorator


classPlanet:
    defdestroy(self):
        print("destroyed")

@mute('destroy')classBorgPlanet(Planet):
    pass

Modifying the __getattribute__ mechanism:

For sake of completeness - what really makes Python reach methods and attributes on the super-class is what happens inside the __getattribute__ call. n the object version of __getattribute__ is where the algorithm with the priorities for "data-descriptor, instance, class, chain of base-classes, ..." for attribute retrieval is encoded.

So, changing that for the class is an easy an unique point to get a "legitimate" attribute error, without need for the "non-existent" descritor used on the previous methods.

The problem is that object's __getattribute__ does not make use of type's one to search the attribute in the class - if it did so, just implementing the __getattribute__ on the metaclass would suffice. One have to do that on the instance to avoid instance lookp of an method, and on the metaclass to avoid metaclass look-up. A metaclass can, of course, inject the needed code:

defblocker_getattribute(target, attr, attr_base):
        try:
            muted = attr_base.__getattribute__(target, '__muted__')
        except AttributeError:
            muted = []
        if attr in muted:
            raise AttributeError("object {} has no attribute '{}'".format(target, attr))
        return attr_base.__getattribute__(target, attr)


definstance_getattribute(self, attr):
    return blocker_getattribute(self, attr, object)


classM(type):
    def__init__(cls, name, bases, namespace):
        cls.__getattribute__ = instance_getattribute

    def__getattribute__(cls, attr):
        return blocker_getattribute(cls, attr, type)



classPlanet(metaclass=M):
    defdestroy(self):
        print("destroyed")

classBorgPlanet(Planet):
    __muted__=['destroy']  #  or use a decorator to set this! :-)pass

Solution 2:

If Undestroyable is a unique (or at least unusual) case, it's probably easiest to just redefine destroy():

classUndestroyable(Planet):

    # ...defdestroy(self):
        cls_name = self.__class__.__name__
        raise AttributeError("%s has no attribute 'destroy'" % cls_name)

From the point of view of the user of the class, this will behave as though Undestroyable.destroy() doesn't exist … unless they go poking around with hasattr(Undestroyable, 'destroy'), which is always a possibility.

If it happens more often that you want subclasses to inherit some properties and not others, the mixin approach in chepner's answer is likely to be more maintainable. You can improve it further by making Destructible an abstract base class:

from abc import abstractmethod, ABCMeta

classDestructible(metaclass=ABCMeta):

    @abstractmethoddefdestroy(self):
        passclassBasePlanet:
    # ...passclassPlanet(BasePlanet, Destructible):

    defdestroy(self):
        # ...passclassIndestructiblePlanet(BasePlanet):
    # ...pass

This has the advantage that if you try to instantiate the abstract class Destructible, you'll get an error pointing you at the problem:

>>> Destructible()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Destructible with abstract methods destroy

… similarly if you inherit from Destructible but forget to define destroy():

classInscrutablePlanet(BasePlanet, Destructible):
    pass

>>> InscrutablePlanet()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class InscrutablePlanet with abstract methods destroy

Solution 3:

Rather than remove an attribute that is inherited, only inherit destroy in the subclasses where it is applicable, via a mix-in class. This preserves the correct "is-a" semantics of inheritance.

classDestructible(object):
    defdestroy(self):
        passclassBasePlanet(object):
    ...

classPlanet(BasePlanet, Destructible):
    ...

classIndestructiblePlanet(BasePlanet):  # Does *not* inherit from Destructible
    ...

You can provide suitable definitions for destroy in any of Destructible, Planet, or any class that inherits from Planet.

Solution 4:

Metaclasses and descriptor protocols are fun, but perhaps overkill. Sometimes, for raw functionality, you can't beat good ole' __slots__.

classPlanet(object):def__init__(self, name):
        self.name = name

    defdestroy(self):
        print("Boom!  %s is toast!\n" % self.name)


classUndestroyable(Planet):
    __slots__ = ['destroy']

    def__init__(self,name):
        super().__init__(name)

print()
x = Planet('Pluto')  # Small, easy to destroy
y = Undestroyable('Jupiter') # Too big to fail
x.destroy()
y.destroy()

Boom!  Pluto is toast!

Traceback (most recent call last):
  File "planets.py", line 95, in <module>
    y.destroy()
AttributeError: destroy

Solution 5:

You cannot inherit only a portion of a class. Its all or nothing.

What you can do is to put the destroy function in a second level of the class, such you have the Planet-class without the destry-function, and then you make a DestroyablePlanet-Class where you add the destroy-function, which all the destroyable planets use.

Or you can put a flag in the construct of the Planet-Class which determines if the destroy function will be able to succeed or not, which is then checked in the destroy-function.

Post a Comment for "How To Make A Class Attribute Exclusive To The Super Class"