我如何使用另一个 class 的魔术方法?
How do i use magic methods from another class?
所以我正在尝试在另一个 class 中使用一个 class 的魔法方法,它继承了那个 class。
基本上我想在下面做的...
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???
谢谢你,我真的很困惑他
只是为了将两个评论转换为一个独立的答案:如果 __magicmethod__
是具有关联运算符的知名评论之一(如 __eq__
是,只需使用运算符访问它.如果没有,干脆“直接调用”:
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)
然后像这样使用:
>> 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
真的没什么特别的。
所以我正在尝试在另一个 class 中使用一个 class 的魔法方法,它继承了那个 class。 基本上我想在下面做的...
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???
谢谢你,我真的很困惑他
只是为了将两个评论转换为一个独立的答案:如果 __magicmethod__
是具有关联运算符的知名评论之一(如 __eq__
是,只需使用运算符访问它.如果没有,干脆“直接调用”:
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)
然后像这样使用:
>> 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
真的没什么特别的。