在Python中创建一个简单的对象层次结构时,我希望能够从派生类中调用父类的方法.在Perl和Java中,有一个关键字this(super).在Perl中,我可能会这样做:
package Foo;
sub frotz {
return "Bamf";
}
package Bar;
@ISA = qw(Foo);
sub frotz {
my $str = SUPER::frotz();
return uc($str);
}
Run Code Online (Sandbox Code Playgroud)
在python中,似乎我必须从子级明确命名父类.在上面的例子中,我必须做类似的事情Foo::frotz().
这似乎不对,因为这种行为使得很难制作深层次结构.如果孩子需要知道哪个类定义了一个继承的方法,那么就会产生各种各样的信息痛苦.
这是python中的实际限制,是我理解中的差距还是两者兼而有之?
我正在尝试学习Python中的super()函数.
我以为我掌握了它,直到我看到这个例子(2.6)并发现自己卡住了.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "test.py", line 9, in do_something
do_something = classmethod(do_something)
TypeError: unbound method do_something() must be called with B instance as first argument (got nothing instead)
>>>
Run Code Online (Sandbox Code Playgroud)
当我在示例之前读到这一行时,这不是我的预期:
如果我们使用类方法,我们没有一个实例来调用super.幸运的是,对于我们来说,super甚至可以使用类型作为第二个参数.---类型可以直接传递给super,如下所示.
通过说do_something()应该用B的实例调用,这正是Python告诉我的不可能.
假设我有一堂课
class SimpleGenerator(object):
@classmethod
def get_description(cls):
return cls.name
class AdvancedGenerator(SimpleGenerator):
@classmethod
def get_description(cls):
desc = SimpleGenerator.get_description() # this fails
return desc + ' Advanced(tm) ' + cls.adv_feature
Run Code Online (Sandbox Code Playgroud)
现在我已经扩展了上面的每个类,每个类都有一个具体的类:
class StringGenerator(SimpleGenerator)
name = 'Generates strings'
def do_something():
pass
class SpaceShuttleGenerator(AdvancedGenerator)
name = 'Generates space shuttles'
adv_feature = ' - builds complicated components'
def do_something():
pass
Run Code Online (Sandbox Code Playgroud)
现在让我说我打电话
SpaceShuttleGenerator.get_description()
Run Code Online (Sandbox Code Playgroud)
问题在于,AdvancedGenerator我希望在SimpleGenerator传递类的实例时调用该方法,具体而言SpaceShuttleGenerator.可以这样做吗?
注意:示例是简化的,因为我的具体示例涉及更多.让我们说我的目标不是连接字符串.