如果类中有一个大方法需要多次调用静态方法,则可以定义一个本地函数对象并将该方法分配给它,以便可以改为调用此函数。
对于静态方法gdc:class Fraction(object):
def __init__(self, a, b):
gcd = Fraction.gcd
if( gcd(a,b) > 1):
d = gcd(a,b)
self.num = a/d
self.denom = b/d
else:
self.num = a
self.denom = b
@staticmethod
def gcd(a,b):
if a > b: a,b = b,a
while True:
if b % a == 0: return a
a, b = b%a, a
def __repr__(self):
return str(self.num) + "/" + str(self.denom)
例如方法gdc:class Fraction(object):
def __init__(self, a, b):
gcd = self.gcd
if( gcd(a,b) > 1):
d = gcd(a,b)
self.num = a/d
self.denom = b/d
else:
self.num = a
self.denom = b
def gcd(self,a,b):
if a > b: a,b = b,a
while True:
if b % a == 0: return a
a, b = b%a, a
def __repr__(self):
return str(self.num) + "/" + str(self.denom)
所以gcd = Fraction.gcd
以及gcd = self.gcd
将允许您调用(根据您的请求,开头不带分数:)gcd(a,b)
另外,如果您想要一些python类和实例/静态方法的基本示例
看看我的一些博客文章,特别是“Jython中的Factorial和Fibonacci”: