+ 6
Can a python class delegate to another class?
Lets say we have the built_in class str. We say def class mystring(str): ... Now in my special prog standard strings shall behave like mystring. Is it possible?
20 Respostas
+ 5
This is the closest I could get.
I use the unittest.mock library. But you need to wrap your string into str(...) for it to take effect.
https://code.sololearn.com/cA0A5a12A8a3/?ref=app
+ 4
https://code.sololearn.com/cuaZYJwGUPDb/?ref=app
+ 4
https://code.sololearn.com/cA51a20A9A7a/?ref=app
Forbiddenfruit does really work nicely š
Zen Coding thank you for the highlight!
But it is really a double-edged sword, the more methods you want to override, you will be in a difficult position because you are not allowed to use in the implementation those methods that were changed to bogus!
+ 3
Oma Falk Can you provide more clarification or a specific use case of what you mean by:
str.delegate(subclassOfString)
Are you using that method name generically or is it meant to refer to a design pattern?
Perhaps, this link is what you're looking for.
https://programmingideaswithjake.wordpress.com/2015/05/23/JUMP_LINK__&&__python__&&__JUMP_LINK-decorator-for-simplifying-delegate-pattern/
+ 2
Oma Falk I didn't understand your question. Did you mean to totally mask the str class with another name?
+ 2
Zen Coding yes...seens to be the only
+ 1
Calvin Thomas
yes mystring inherits from str, redefines and adds some methods and after I hoped for
str. delegate(mystring)
+ 1
David Carroll
str.delegate(mystring) means whenever a method m of object str is called, the real call is mystring.m()
Since mystring inherits from str, the call is save.
Str and mystring is an example, it counts for all objects and their children.
+ 1
Oma Falk This does the job I guess:
str = mystring
+ 1
Calvin Thomas I guessed too butš¢š¢
+ 1
Calvin Thomas I am not sure, if that works.
Let's say you have your own split method in mystring.
str = mystring
"Blub". split('/')
Would the second line call mystring.split()?
+ 1
Oma Falk In my stackoverflow the solution uses a library called forbiddenfruit. https://pypi.org/project/forbiddenfruit/
I think that is close to what you want.
0
I doped that works. You could probably shadow 'str' by your class but probably only in a limited scope
0
Zen Coding ohhh it goes deeeeep into Cpython.
BUT...nice!ššš
0
Oma Falk Did you mean this:
class newString(str):
def foo(self, x):
print(x)
# TEST
str = newString("FOO")
0
Oma Falk What had gone wrong? A better explanation helps.
0
Zen Coding and Oma Falk I guess that Python was designed to consider anything surrounded by quotes as a string object, regardless of the external variable 'str'. The actual class isn't cleared from the heap even though the reference is lost. This is a built-in functionality, I guess.
0
I don't know what's happening here:
del __builtins__.str
print(type("a"))
P.S. David Carroll Would love to receive some help on this matter.