[英]How do you call a method both “inside” and “outside” an instance in python?
我真的不知道如何描述这一点,但一个例子是:在 Sympy 中,如果你想获得一个表达式的共轭,你可以这样做
from sympy.abc import x
x.conjugate()
或者
from sympy.abc import x
from sympy import conjugate
conjugate(x)
我认为这里发生的是 x.conjugate 将返回一个 function ,其中 x 作为参数。 是否有一种简单或“标准”的方式来实现这样的功能?
只需根据另一个实现一个:
# Approach 1
def conjugate(thing):
# logic goes here
class Thing:
# This looks strange, but inside the method, the global version is looked up.
def conjugate(self):
return conjugate(self)
x = Thing() # create the instance used elsewhere
# Approach 2
class Thing:
def conjugate(self):
# logic goes here
x = Thing() # create the instance used elsewhere
def conjugate(thing):
return thing.conjugate() # use the method.
# Or you can alias the method this way:
# conjugate = Thing.conjugate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.