标签: super

我正确使用super()吗?

我做了一小部分代码因为我还在试图弄清楚使用的具体细节super().为什么这个块会运行到这个TypeError

 a = SecondClass()
TypeError: __init__() takes exactly 2 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)

然后,该SecondClass.meth()函数应该打印字符串,但我显然在概念上遗漏了一些东西.

class FirstClass (object):
    def __init__ (self, value):
        self.value = value
        print self.value

class SecondClass (FirstClass):
    def meth (self):
        super (FirstClass,self).__init__(value = "I am a strange string")

a = SecondClass()
a.meth()
Run Code Online (Sandbox Code Playgroud)

python oop inheritance super

6
推荐指数
1
解决办法
1534
查看次数

你怎么知道是否在Objective C中调用超类方法

Class Child扩展Parent.父实现协议C,它具有可选方法,包括-(void)d.孩子有执行-d; 应该调用[super d]吗?

换句话说,[super d]当且仅当某些内容会响应时,我会编写什么代码来调用?假设我不控制Parent的实现; 它可能随时改变.

这是我想到的所有方法.我目前正在使用4号.

显然是明智的答案1:

[super d]; // Delete this line if a runtime exception occurs when you try it
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为Parent可能会动态实现-d,因此当您测试它而不是在字段中时,它会起作用.或者Parent的实现可能会更改,以便此测试的结果不再正确.

显然是明智的回答2:

if ([super respondsToSelector:_cmd])
    [super d];
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为NSObject的-respondsToSelector实现将在Child中找到实现并在所有情况下返回YES.

显然是明智的答案3:

if ([[self superclass] instancesRespondToSelector:_cmd])
    [super d];
Run Code Online (Sandbox Code Playgroud)

当且仅当超类知道它总是实现-d时,这是有效的; 如果实例动态确定是否存在此方法,则此方法将不起作用.优于1,因为它将在运行时获取对Parent实现的静态更改.

显然是明智的回答4:

@try
{
    [super d];
}
@catch (NSException *exception)
{
    NSString *templateReason = [NSString stringWithFormat:
                                @"-[%@ %@]: unrecognized selector sent to instance %p"
                                ,NSStringFromClass([self superclass])
                                ,NSStringFromSelector(_cmd)
                                ,self];
    if (![exception.reason isEqualToString:templateReason])
        @throw …
Run Code Online (Sandbox Code Playgroud)

objective-c super respondstoselector

6
推荐指数
1
解决办法
868
查看次数

块和对象

我有一个像这样的对象

class SomeObject
  def initialize &block
    # do something
  end
end

class AnotherObject < SomeObject
  def initalize &block
    super
    # do something with block
  end
end
Run Code Online (Sandbox Code Playgroud)

super调用时AnotherObject,块似乎被传递给SomeObject.这是正确的行为吗?

ruby inheritance super ruby-1.9.3

6
推荐指数
1
解决办法
92
查看次数

DoubleRenderError:"在此操作中多次调用渲染和/或重定向"

我想通过role_ids用户重定向:

  • 如果它等于2,则重定向到workers_path.
  • 如果它等于1,则重定向到tasksadmins_path.

我定义了接下来的事情:

class ApplicationController < ActionController::Base
  include ApplicationHelper

  protect_from_forgery
  before_filter :authenticate_user!

  def stored_location_for(user)
    nil
  end

  def after_sign_in_path_for(user)
     if current_user.role_ids == [2]
       return redirect_to(workers_path)
     else
       return redirect_to (tasksadmins_path)
     end
  end
end
Run Code Online (Sandbox Code Playgroud)

但是当我登录时,我遇到了错误:

AbstractController::DoubleRenderError in UserSessionsController#create

Render and/or redirect were called multiple times in this action. Please note 
that you may only call render OR redirect, and at most once per action. Also 
note that neither redirect nor render terminate execution of the action, …
Run Code Online (Sandbox Code Playgroud)

redirect ruby-on-rails super devise internal-server-error

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

了解使用Super访问Superclass成员

我指的是java语言规范,以了解super的用法.虽然我理解第一个用例即

表单super.Identifier引用当前对象的名为Identifier的字段,但将当前对象视为当前类的超类的实例.

我似乎无法理解以下用例:

该表单T.super.Identifier引用了与词汇封闭实例相对应的名称Identifier T,但该实例被视为超类的实例T.

有人可以借助代码解释一下吗?

我想以下可能是第二种情况的说明:

class S{
    int x=0;
}

class T extends S{
    int x=1;
    class C{
        int x=2;
        void print(){

            System.out.println(this.x);
            System.out.println(T.this.x);
            System.out.println(T.super.x);
        }
    }
    public static void main(String args[]){
        T t=new T();
        C c=t.new C();
        c.print();
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:2 1 0

java super

6
推荐指数
1
解决办法
154
查看次数

为什么继承'object'的python类在__init__方法中调用'super'?

我在requests模块的源头四处寻找,并注意到这段代码:

class Response(object):
    """The :class:`Response <Response>` object, which contains a
    server's response to an HTTP request.
    """

    def __init__(self):
        super(Response, self).__init__()
        ... more init method...
Run Code Online (Sandbox Code Playgroud)

我的理解super()表明这个电话根本不会做任何事情.我发现相当的几个问题,关于超通话,但其他类的子类,但并非所有的工作object本身.在python文档,也没有提及这种结构.

在我看来,这可能只是一个错误,如果您git blame将该文件提交给引入该行提交,您将看到在作者身份时,它Response是一个子类BaseResponse.该行只是一个类重构的延续,还是这个super()调用做了什么呢?

python inheritance super python-requests

6
推荐指数
1
解决办法
1406
查看次数

Python:无法使用super()调用父类析构函数

我无法从Child类的析构函数中调用Parent类的析构函数.请检查以下代码:

class BaseClass(object):
    def __del__(self):
        print 'BaseClass->Destructor'

class DerivativeClass(BaseClass):
    def __del__(self):
        print 'DerivativeClass->Destructor'
        #Invoke destructor of the base class, it works 
        BaseClass.__del__(self)           
        #Doesn't work
        #super(DerivativeClass, self).__del__() 

instance = DerivativeClass()
Run Code Online (Sandbox Code Playgroud)

当我使用时super(DerivativeClass, self).__del__(),DerivativeClass.__del__()我收到以下错误:

Exception TypeError: 'must be type, not None' in <bound method 
DerivativeClass.__del__ of <__main__.DerivativeClass object at 0xb73a682c>> ignored
Run Code Online (Sandbox Code Playgroud)

题:

为什么我不能super在子类的析构函数中使用它,而它在子类的构造函数中完全没问题?

python destructor super

6
推荐指数
1
解决办法
3848
查看次数

在super.method之前或在android中的super.method之后的逻辑是什么?

大家好我想问一下,如果我在super.onDestroyView()之前写了什么东西有什么区别; 并在super.onDestroyView()之后; 见下面的例子

在super.ondestoryview()之前删除片段;

@Override
    public void onDestroyView() {

        try {
            Fragment fragment = (getFragmentManager()
                    .findFragmentById(R.id.mapviews));
            FragmentTransaction ft = getActivity().getSupportFragmentManager()
                    .beginTransaction();
            ft.remove(fragment);
            ft.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroyView();
    }
Run Code Online (Sandbox Code Playgroud)

在super.ondestoryview()之后删除片段;

@Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            Fragment fragment = (getFragmentManager()
                    .findFragmentById(R.id.mapviews));
            FragmentTransaction ft = getActivity().getSupportFragmentManager()
                    .beginTransaction();
            ft.remove(fragment);
            ft.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
Run Code Online (Sandbox Code Playgroud)

methods android super

6
推荐指数
1
解决办法
752
查看次数

在这个Java示例中对"super"关键字感到困惑

在java网站的教程页面上的这个例子中.两个接口定义相同的默认方法startEngine().类FlyingCar实现两个接口,并且必须覆盖,startEngine()因为存在明显的冲突.

public interface OperateCar {
    // ...
    default public int startEngine(EncryptedKey key) {
        // Implementation
    }
}
public interface FlyCar {
    // ...
    default public int startEngine(EncryptedKey key) {
        // Implementation
    }
}

public class FlyingCar implements OperateCar, FlyCar {
    // ...
    public int startEngine(EncryptedKey key) {
        FlyCar.super.startEngine(key);
        OperateCar.super.startEngine(key);
    }
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么,from FlyingCar,super用于指代startEngine()in OperateCarFlyCarinterfaces的两个版本.据我所知,startEngine()没有在任何超类中定义,因此不应该被称为居民.我也没有看到super和实现的两个接口之间有任何关系FlyingCar

java interface super java-8 default-method

6
推荐指数
2
解决办法
1543
查看次数

Python 3,super .__ del __()

__del__在我定义的类中有一个方法,删除一些通过在ctypes接口中调用C++ new创建的C++对象.我想删除我的类的实例时删除这些对象.我有一个这里显示的类的片段:

class Graph(QtCore.QObject):
    def __init__(self):
        super().__init__()
        #list of objects created by calls to ctypes to create pointers to C++ objects which are instantiated with C++ new 
        self.graphs = []

    def __del__(self):
        print("in delete method")
        for graph in self.graphs:
            # call the C++ delete to free the storage used by this graph
            myctypes.graphDelete(graph)
        super().__del__()
Run Code Online (Sandbox Code Playgroud)

当我的Graph类的一个实例被删除时,该__del__方法被调用,我看到我的print语句,当我在C++代码中的析构函数方法中设置一个断点时,正如预期的那样,它删除了该对象.但是,当我的__del__方法调用时super().__del__(),我收到错误消息:

super().__del__()
AttributeError: 'super' object has no attribute '__del__'
Run Code Online (Sandbox Code Playgroud)

如果我__del__在子类中定义自己的方法或者是否会自动删除父类,如何确保删除父类(QtCore.QObject)?

python destructor super python-3.x

6
推荐指数
2
解决办法
2131
查看次数