在类外部定义的方法,其本身随后被导入

时间:2016-03-16 10:50:39

标签: python python-2.7 object methods

可以定义特定类之外的函数,在类中使用它们,然后将该类导入其他地方并使用它吗?

是否存在与此相关的风险,而不是制作该类的所有函数方法?

我在python 2.7中编写此代码

例如,创建一个这样的类:

def func(a):
    return a

class MyClass():

    def class_func(self, thing):
        return func(thing)

然后将MyClass导入另一个python脚本并使用其class_func方法。

2 个答案:

答案 0 :(得分:1)

没关系,但如果func仅在MyClass中使用,那么将staticmethod设为MyClass并将class_func置于class MyClass(object): @staticmethod def _func(a): return a def class_func(self, thing): return type(self)._func(thing) 附近可能会有所帮助}:

$plazas = DB::table('clase_schedule')->select(['schedule_id', DB::raw('SUM(capMax) as capMax')])->groupBy('schedule_id')->first();

答案 1 :(得分:1)

这样做是可以的,实际上是python的语言功能。函数可以访问它们所定义范围的名称,无论它们从何处被调用。

例如,你也可以这样做:

factor = 2
def multiply(num):
    return num*factor

有关背景信息,请参阅this post

"风险"与此相关的是外部名称​​显式不受您的控制。它可以由你的程序的其他部分自由修改,但没有明确的含义。

考虑这个例子:

def func(a):
  return a

class MyClass(object): # note: you should inherit from object in py2.X!
  def class_func(self, thing):
    return func(thing)

myinstance = MyClass()
foo = myinstance.class_func(1)

def func(a):
  return str(a)

bar = myinstance.class_func(1)

此处,foobar会有所不同,即整数1和字符串"1"

然而,通常,使这成为可能是使用这种结构的全部要点。