Ask Your Question
0

How can an attribute be added to a wrapped instance method in Wrapt?

asked 2022-07-18 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-07-21 10:00:00 +0000

david gravatar image

To add an attribute to a wrapped instance method in Wrapt, you can use the ObjectProxy class provided by Wrapt. Here's an example:

from wrapt import ObjectProxy

class MyClass:
    def my_method(self):
        print("Hello, world!")

wrapped_method = ObjectProxy(MyClass().my_method)
wrapped_method.new_attribute = "I am a new attribute!"

print(wrapped_method.new_attribute) # prints "I am a new attribute!"
wrapped_method() # calls the original method, prints "Hello, world!"

In this example, we create an instance of MyClass and wrap its my_method method using ObjectProxy. Then, we add a new attribute new_attribute to the wrapped method. Finally, we can access the new attribute and call the original method via the wrapped method.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-07-18 11:00:00 +0000

Seen: 19 times

Last updated: Jul 21 '22