相关疑难解决方法(0)

从Python中的子类调用父类的方法?

在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 inheritance class object

553
推荐指数
11
解决办法
59万
查看次数

使用super与类方法

我正在尝试学习Python中的super()函数.

我以为我掌握了它,直到我看到这个例子(2.6)并发现自己卡住了.

http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#super-with-classmethod-example

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告诉我的不可能.

python class object super class-method

68
推荐指数
2
解决办法
4万
查看次数

如何从Python中重写的@classmethod调用父类的@classmethod?

假设我有一堂课

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.可以这样做吗?

注意:示例是简化的,因为我的具体示例涉及更多.让我们说我的目标不是连接字符串.

python class-method superclass

4
推荐指数
1
解决办法
2875
查看次数

标签 统计

python ×3

class ×2

class-method ×2

object ×2

inheritance ×1

super ×1

superclass ×1