r/PythonLearning 1d ago

Python Classes question

Is there a way to pass the instantiating object name to the class as you call it, without specifically putting the name in the parentheses? I'm trying to create a PyGame terminal emulator that has the same frontend functionality as Curses. I've figured out that I can create windows in the same way, except that instead of being able to do windowname.newwin(size), I have to do windowname.curses()\nwindowname.newwin(size). Presumably, I could also do windowname.newwin(size, windowname), but I'd prefer being able to use the exact same syntax as Curses.

The reason for using the same syntax is because I want to be able to decide where it renders (real terminal or PyGame) based on which module gets imported.

If there is a way to do this, please let me know.

3 Upvotes

6 comments sorted by

3

u/Sea-Ad7805 1d ago

If different APIs differ but you want to use them in the same way, then write your own abstraction that makes the translation to the different APIs.

2

u/Mathie1729 1d ago

Adapter pattern is probably the search term you want for that.

1

u/blockCoder2021 1d ago

I’m not trying to make two different existing APIs work the same way; I’m trying to make a custom API work like an existing one. My main problem currently is that I’m not certain how to condense those two lines together. What I’m trying to do is be able to create windows of a custom name (windowname) and have that name get assigned. If I could trigger the __init__ function with the object name as the argument, I think I’d be fine, but I’m not sure how to do that.

1

u/Sea-Ad7805 1d ago

When you call __init__ the object and its name doesn't exists yet. If you show clear runnable example code your questions would be much better.

1

u/SnooCalculations7417 14h ago edited 14h ago

def __init__(self, MyClass):     self.myclass = MyClass()

Or  ``` def init(self, MyClass):     self.myclass = init_myclass()

def init_myclass(self):     ...     return MyClass() ```

1

u/codeguru42 13h ago

It sounds like you are describing a potential solution to a problem you encountered without fully explain the original problem. If you provide more details, then we can probably give better feedback.

With the information giving, I agree with another post that you might be looking for the adapter pattern.