【发布时间】:2018-12-19 16:51:02
【问题描述】:
我有类似以下的内容:
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(self, 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)
而且它有效!但是我仍然想知道这是否是一种很好的做事方式?
【问题讨论】:
-
如果你想使用没有实例的实例方法,那么它不应该是实例方法。
-
What the others say and
self.method()只是klass.method(self)的缩写,它允许您在 Class2 中调用Class1.print_me(self, string)。
标签: python python-3.x class inheritance