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

时间:2018-09-18 15:01:44

标签: python class

因此,到目前为止,我有一个函数可以用作类中的方法。
现在,我想在不创建类实例的情况下使用它。

无需大量更改代码的最佳方法是什么?

示例代码如下:

之前:

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} }。

我的想法:

method1

-

这是不好的做法吗?
还有人怎么可以从类内部调用方法?或者,一个类如何在其外部合并方法方法?

4 个答案:

答案 0 :(得分:0)

由于self参数而无法使用。而是这样定义它:

class A(object):
    def method1(self, input):
        return method1(input)

答案 1 :(得分:0)

尝试一下:

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)

这称为静态方法,为此,您的函数不能包含(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

答案 3 :(得分:0)

将不需要或不希望使用其类实例的方法转换为静态方法。 想法如下:

>>> 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
>>> 

请注意,从正常方法到静态方法的区别。在静态对象上,您省略了self参数,因此,您不需要其类的实例即可使用该静态方法。