代码之家  ›  专栏  ›  技术社区  ›  SuperCiocia

在类内部和外部使用方法-python

  •  0
  • SuperCiocia  · 技术社区  · 6 年前

    所以我有一个函数,到目前为止,我在一个类中有一个方法。
    结果是现在我想在不生成类实例的情况下使用它。

    在不需要大量修改代码的情况下,最好的方法是什么?

    示例代码如下:

    之前:

    class A(object):
     def method1(self, input):
      return input*3 + 7
     def method2(self, input):
      return self.method1(input) + 4
    

    基本上我想 method1 离开类,这样我就可以使用它而无需创建 A ,但也不想改变 self.method1 方法1 到处都是。

    我的想法是:

    def method1(input):
     return input*3 + 7
    
    class A(object):
     def __init__(self):
      self.method1 = method1
     def method2(self, input):
      return self.method1(input) + 4
    

    ——

    这是不好的做法吗?
    另外,如何从类内部调用方法?或者,一个类如何在它之外包含方法方法?

    4 回复  |  直到 6 年前
        1
  •  0
  •   Mohammad Zain Abbas    6 年前

    试试这个:

    def method1(input):
     return input*3 + 7
    
    class A(object):
        def method1(self, input):
            return method1(input)
    
        def method2(self, input):
            return self.method1(input) + 4
    

    这应该管用

        2
  •  0
  •   Aran-Fey Kevin    6 年前

    它不起作用,因为 self 参数。而是这样定义:

    class A(object):
        def method1(self, input):
            return method1(input)
    
        3
  •  0
  •   vash_the_stampede    6 年前

    这叫A 静态法 为此,函数不能包含 (self)

    class A(object):
    
        def method_one(variable):
            return variable * 3 + 7
    
        def method_two(self, variable):
            return self.method_one(variable) + 4
    
    print(A.method_one(10))
    
    (xenial)vash@localhost:~/python/stack_overflow$ python3.7 method_out.py 
    37
    
        4
  •  0
  •   R.R.C.    6 年前

    将不需要或不需要类实例的方法转换为StaticMethod。 Ideia如下所示:

    >>> class A:
        @staticmethod
        def m(value):
            return value*3+7
        def sum(self, value):
            return self.m(value) + 4
    
    
    >>> a = A()
    >>> a.sum(4)
    23
    >>> 4+A.m(4)
    23
    >>> 
    

    注意从普通方法到静态方法的区别。在静态方法中,您将自己的参数设置为commit,这意味着您不需要其类的实例来使用该静态方法。