Adapter to add new method

I don't know if I understood right from the documentation.

But if i create an adapter on the configure.zcml to add a new method to a class I will be able to instantiate that class and use that method?

For example, i tried to extend the class "SessionDataManager" because on some files I want to use this new method.

I want on python files:

context.session_data_manager.myCustomMethod()

so on the configure.zcml i inserted

<adapter factory=".myfile.FactoryMyClass" />

file myfile.py and on the class

from .interface-myfile import IMyClass

from zope.component import adapter
from zope.interface import Interface, implements, implementer

from Products.Sessions.interfaces import ISessionDataManager


@implementer(ISessionDataManager)
@adapter(IMyClass)
class FactoryMyClass(object):

#implements(ISessionDataManager)

def __init__(self, context):
    self.context = context

def myCustomMethod(self):
    return 'my custom logic'

file interface-myfile

from zope.interface import Interface

class IMyClass(Interface):
""" comment """

When calling context.session_data_manager.myCustomMethod() it always show the error

AttributeError: myCustomMethod

I looked a bunch of plone files that do the same pattern, but i can't make it work

Thanks.

An adapter neither adds a method to an existing class nor to an instance of a class - this would be classed "Monkey patching" or you would use class inheritance for creating your own implementation of class (which is not appropriate here). Adapters do not add anything magically to existing implementations. They adapt your current object and create something new (as you can see from your own adapter implementation). You custom logic in myCustomMethod will make use of self.context - which is the adapted or wrapped object. The implementation - as said - does not extend the functionality of the class of context.

An adapter wraps an instance of a given class and provides additional functionality through its defined interface. So you usually need

adapted = IMyAdapter(some_object)
adapted.myCustomMethod()

https://zopeinterface.readthedocs.io/en/latest/README.html#adaptation

on the docs says "Adapters make it possible to extend the behavior of a class without modifying the class itself." and I thought that "the class" would be the original class because I was not "modifying" it.

Thanks very much for the reply.

"Adaptation" is a widely known design pattern available in many different language..that's how is works.

some theory https://en.wikipedia.org/wiki/Adapter_pattern

1 Like

thanks :smile:

1 Like

Plone Foundation Code of Conduct