0

So I'm trying to use a magic method from one class in another class that inherits that class. basically what im trying to do below...

class Class1: def __magicmethod__(self, arg1, arg2): #blah blah class Class2(Class1): def func1(self, x, y): #what do type here to use the magic method??? 

thank you, I'm really confused about his

4
  • 2
    You dont call them directly - you call the wrapping method that will call the magic method. Example:__eq__ => == Commented Oct 5, 2021 at 14:48
  • Just call it directly: c = Class1(); c.__magicmethod__(x, y) Commented Oct 5, 2021 at 14:49
  • @quamrana is there another way to write it like magicmethod( ...)? Commented Oct 5, 2021 at 14:56
  • It depends on the actual magic method. You should look up a list of them. Please update your question with a couple of concrete methods you are interested in. Commented Oct 5, 2021 at 14:58

1 Answer 1

2

Just to transform both comments to a self-contained answer: If __magicmethod__ is one of the well-known ones with associated operator (like __eq__ is, simply use the operator to access that. If not, simply "call it directly":

class Class1: def __eq__(self, other): print(f"== from {self} with {other} here!") def __magicmethod__(self, arg1, arg2): print(f"{self}({arg1}, {arg2})") class Class2(Class1): def eq(self, other): self == other def func1(self, x, y): self.__magicmethod__(x, y) 

And then use like:

>> c2 = Class2() >>> c2.func1("x", "y") <__main__.Class2 object at 0x0000021B8694A1F0>(x, y) >>> c2 == "foo" == from <__main__.Class2 object at 0x0000021B8694A1F0> with foo here! >>> c2.eq("foo") # same as before, but through your own method 

Nothing special really.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.