Sturm
Sturm

Reputation: 4125

Rename every method skipping the object name

Not sure if this is a valid question or just nonsense, but I have not found an answer online.

I know that it is possible to rename a function in Python this way:

SuperMethod = myObject.SuperMethod

I would like to know if it is possible to rename every method of an object, that's it, being able to call every method of a particular object without telling explicitly its name (similarly than in VBA by using with clause)

I know this will have all kind of naming issues.

Upvotes: 1

Views: 58

Answers (1)

blhsing
blhsing

Reputation: 106792

You can update the globals() dict with the object's callables after filtering out the internal methods that start and end with '__':

class A:
    def __init__(self, i):
        self.i = i
    def x(self):
        print(self.i + 1)
    def y(self):
        print(self.i + 2)
myObject = A(1)
globals().update({k: getattr(myObject, k) for k, v in A.__dict__.items() if not k.startswith('__') and not k.endswith('__') and callable(v)})
x()
y()

This outputs:

2
3

Upvotes: 1

Related Questions