如何在不初始化第一个类的情况下从另一个类调用一个类方法?

时间:2018-07-11 15:14:03

标签: python python-3.x class inheritance

我有如下内容:

class Class1(object):
    def __init__(self):
        print('I've init-ed')
    def print_me(self, string):
        print(string)

class Class2(object):
    def __init__(self):
        print('Class 2 init')
    def print_me_from_other_class(self, string):
        Class1().print_me(string)

然后,如果我打电话给类似的人

test = Class2()
test.print_me_from_other_class('TEST')

然后我得到:

Class 2 init
I've init-ed
TEST

我想做的是从Class2中的方法中调用Class1中的方法,但不从类1中调用 init 。所以我最终得到:

Class 2 init
TEST

我试图在print_me_from_another_class(s​​elf,string)函数的Class1之后删除括号,所以它说:

print_me_from_another_class(self, string):
    Class1.print_me(string)

但这会引发错误:

TypeError: print_me() missing 1 required positional argument: 'string'

有什么想法吗?还是这是处理问题的不好方法?似乎它将节省重写代码,因此应该是一件好事。

编辑:

我已经确定需要将Class2的实例传递给该函数,以便Class2中的函数变为:

def print_me_from_other_class(self, string):
    Class1.print_me(self, string)

它有效!但是我仍然想知道这是否是一个很好的做事方法?

4 个答案:

答案 0 :(得分:1)

请注意print_me中的“ self”参数-这意味着必须在Class1的特定实例上调用函数 。您想要的是一个静态函数。下面的代码演示了这一点。

class Class1(object):
    def __init__(self):
        print("I've init-ed")
    @staticmethod
    def print_me(string):
        print(string)

class Class2(object):
    def __init__(self):
        print('Class 2 init')
    def print_me_from_other_class(self, string):
        Class1.print_me(string)


test = Class2()
test.print_me_from_other_class('TEST')

输出:

Class 2 init
TEST

答案 1 :(得分:1)

您的代码块的问题是Class1.print_me(string)创建了新对象,这就是为什么要调用init方法来避免这种情况的原因。简单的解决方案是使用继承。

class Class1(object):
    def __init__(self):
        print('Ive init-ed')
    def print_me(self, string):
        print(string)

class Class2(Class1):
    def __init__(self):
        print('Class 2 init')
    def print_me_from_other_class(self, string):
        self.print_me(string)
obj=Class2()
obj2.print_me_from_other_class("hi")

您也可以直接调用基类函数     obj2.print_me("hello")

答案 2 :(得分:0)

您是否尝试过@staticmethod?像这样:

class C1:
 def __init__(self):
  print "C1 INIT"
 def f(self):
  C2.c()

class C2:
 def __init__(self):
  print "C2 INIT"
 @staticmethod
 def c():
  print "method c from C2"

@staticmethod装饰器用于制作静态方法,通常,当您要调用无需初始化类的方法时,这种方法很有用。是组织功能的好方法。

答案 3 :(得分:0)

解决方案

感谢大家的帮助,我现在对它有了更好的了解。最后,我在注释中提出的建议是从类中删除这些特定方法,并使它们成为全局函数。我实际上经过并删除了所有未专门引用self的方法(或将它们保留为类方法是有意义的),并使其成为全局方法。现在来看,我认为这是一种更好的代码结构方式。

谢谢。