标签: super

Powermock - 模拟超级方法调用

这是我的代码 -

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;

import org.powermock.core.classloader.annotations.*;
import static org.powermock.api.support.SuppressCode.*;

class BaseService {
    public int save() {
        validate();
        return 2;
    }

    public static int save2() {
        return 5;
    }

    public void validate() {
        System.out.println("base service save executing...");
    }
}

class ChildService extends BaseService {
    public int save() {
        System.out.println("child service save executing...");
        int x = super.save2();
        int y = super.save();
        System.out.println("super.save returned " + y);
        load();
        return 1 + x;
    }

    public void load() {
        System.out.println("child service …
Run Code Online (Sandbox Code Playgroud)

java super mockito powermock

5
推荐指数
1
解决办法
8810
查看次数

DeviceAdminReceiver 中的空构造函数异常

E/AndroidRuntime(27856): java.lang.RuntimeException: Unable to instantiate receiver com.inc.statusbar.Statusbar$DeviceAdminSampleReceiver: java.lang.InstantiationException: can't instantiate class com.inc.statusbar.Statusbar$DeviceAdminSampleReceiver; no empty constructor
Run Code Online (Sandbox Code Playgroud)

我已经尝试调用DeviceAdminReceiver类的默认构造函数但无济于事。删除构造函数也给出了同样的错误。 DeviceAdminSampleReceiver类定义 -

public class DeviceAdminSampleReceiver extends DeviceAdminReceiver
{

    public DeviceAdminSampleReceiver()
    {
        super();    
    }

    @Override
    public void onEnabled(Context context, Intent intent) {
        super.onEnabled(context, intent);
    }

    @Override
    public CharSequence onDisableRequested(Context context, Intent intent) {
        super.onDisabled(context, intent);
        return "admin_receiver_status_disable_warning";
    }

    @Override
    public void onDisabled(Context context, Intent intent) {
        super.onDisabled(context, intent);
    }

}
Run Code Online (Sandbox Code Playgroud)

android constructor super broadcastreceiver device-admin

5
推荐指数
0
解决办法
252
查看次数

如何模拟超级引用(在超级类上)?

有时,当我编写单元测试时,我应该模拟对超类的引用。

我已经阅读了这个问题: 问题

这个答案回答了重构代码的DI建议。但我做不到

如果超类方法足够大,这个答案另一个答案不合适。就我而言,我有非常大的代码。是的,我知道这违反了 SOLID OOD 原则,但我应该编写测试。我没有足够的时间进行重构。

这个问题是 4 年前提出的!

目前 Mockito 或 Powermock 可以解决这个问题吗?

更新

代码示例:

class BaseService {  
    public void save() {
      // a lot of code here! I cannot change this code.
    }  
}

public Childservice extends BaseService {  
    public void save(){  
        //logic for testing
        super.save();
       //logic for testing
    }  
} 
Run Code Online (Sandbox Code Playgroud)

更新 2

public class Parent {
    public int save() {
         return 99;
    }   
}

public class Child extends Parent …
Run Code Online (Sandbox Code Playgroud)

java unit-testing mocking super powermock

5
推荐指数
1
解决办法
9143
查看次数

Ruby 中的“super”是什么?

在 Internet 上浏览有关 ruby​​ on rails 的信息时,我看到了super. 有人能说出它是什么以及它能做什么吗?

ruby super

5
推荐指数
1
解决办法
1万
查看次数

IPython autoreload为重复调用Python2 super()提供错误

我正在一个IPython笔记本中的原型,它从我的计算机上的模块加载Python2代码.我激活了重新加载魔术命令,以便在我进行代码更改并重新运行单元格以查看其影响时,更容易在文本编辑器和笔记本之间来回切换:

%reload_ext autoreload
%autoreload 2
Run Code Online (Sandbox Code Playgroud)

我在Python 2.7.10中工作,因为我使用了一些不能编译的遗留代码.我的部分工作是扩展这些遗留代码中的一些类并重载它们的一些方法.但是,我还需要调用一些原始的基本方法来完成重要的工作.例如:

class LegacyBase:

    def important_method(self):
        #old stuff i'll need

class NewClass(LegacyBase):

    #overload base method
    def important_method(self):
       #do some new stuff

       while 1:
           #call old method to do stuff
           super(NewClass, self).important_method() #use old Python2 super calls :(

           #some break conditions
Run Code Online (Sandbox Code Playgroud)

当我第一次在我的笔记本中调用important_method()某个NewClass实例时(意味着,在内核重置后),它运行正常.循环使得super呼叫不止一次发生!没有错误

但是,如果我去修改一些代码来我的新方法,在我的文本编辑器,并回到IPython的细胞并再次调用它,我得到以下错误在我的重载线路important_method(),其中super呼叫.

TypeError: super(type, obj): obj must be an instance or subtype of type
Run Code Online (Sandbox Code Playgroud)

注意:我尝试将新方法命名为另一个名称,因为我认为这与重载方法再次调用自身有关,但这没有帮助.此外,我希望它们是相同的名称,因为这是一个API方法,我希望遗留代码的用户能够调用他们之前知道的相同方法.

知道如何使用这些Python2 super调用在IPython笔记本中重新加载吗?

谢谢!

python super python-2.7 ipython-notebook

5
推荐指数
1
解决办法
716
查看次数

在 Python 中,如何避免在派生自在其 __new__ 中带有 super() 的类的类中调用 __init__ 两次:

我是python的新手。不知何故

__init__
Run Code Online (Sandbox Code Playgroud)

对于从另一个类派生的类调用两次

super()
Run Code Online (Sandbox Code Playgroud)

我的问题是如何避免这种情况,因为我在那里进行了非常昂贵的计算。

class A(object):
  def __new__(cls, *args, **kwargs):
    print("Class A: __new__")
    obj = super(A, cls).__new__(cls) # super is used here
    obj.__init__(*args, **kwargs)
    return obj
  def __init__(self, x):
    self.attrib = x+1

class B(A):
  def __init__(self, x):
    print("Class B: __init__")
    self.prop = 2*x # some expensive computation

a = A(10) # a test call

b = B(20) # Q: here, how to avoid calling __init__ twice in class B?
Run Code Online (Sandbox Code Playgroud)

编辑:谢谢两位的回答。我的真实代码是使用 scipy 库中内置的 arpack 对角化一个大型稀疏矩阵。我正在调用在 arpack.py 中定义的类 SpLuInv(LinearOperator),其中类 LinearOperator 在 …

python derived-class super

5
推荐指数
1
解决办法
1961
查看次数

从匿名内部类调用重写的默认方法

考虑以下代码:

interface A {
    default void doA() {
        System.out.println("a");
    } 
}

interface B {
    void doB(); 
}

class Test implements A {

    @Override
    public void doA() {        
        // Works
        B b = () -> A.super.doA();
        b.doB();

        // Does not compile
        /*
        new B() {      
            public void doB() {  
                A.super.doA();
            }       
        }.doB();
        */
    }

    public static void main(String[] args) {
        new Test().doA();
    }

}
Run Code Online (Sandbox Code Playgroud)

这是做作,但基本上Test::doA()试图来包装thisB,并且具有B::doB()调用它的超强功能A.super.doA().

我可以打电话给A.super.doA()一个类型的lambda B就好了.但我无法弄清楚A.super.doA() …

java super anonymous-class java-8 default-method

5
推荐指数
1
解决办法
260
查看次数

super(type, obj): obj 必须是 Keras 中 type 的实例或子类型

我实现了以下使用带有 Tensorflow 后端的 Keras 从头开始​​构建微型 yolo v2

我的代码在 Keras 2.1.5 中运行良好但是当我更新到 Keras 2.1.6 时我遇到了错误

""kernel_constraint=无,

TypeError: super(type, obj): obj must be an instance or subtype of type "" 请帮帮我,非常感谢

import tensorflow as tf
import keras
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten, 
Reshape, LeakyReLU, BatchNormalization 

def yolo():
    model = Sequential()
    model.add(Conv2D(16,(3,3), padding='same',input_shape=(416,416,3),data_format='channels_last'))
    model.add(LeakyReLU(alpha=0.1))
    model.add(MaxPooling2D(pool_size=(2,2)))

    model.add(Conv2D(32,(3,3), padding='same'))
    model.add(BatchNormalization(axis=-1))
    model.add(LeakyReLU(alpha=0.1))
    model.add(MaxPooling2D(pool_size=(2,2)))

    model.add(Conv2D(64,(3,3), padding='same'))
    model.add(BatchNormalization(axis=-1))
    model.add(LeakyReLU(alpha=0.1))
    model.add(MaxPooling2D(pool_size=(2,2)))

    model.add(Conv2D(128,(3,3), padding='same'))
    model.add(BatchNormalization(axis=-1))
    model.add(LeakyReLU(alpha=0.1))
    model.add(MaxPooling2D(pool_size=(2,2)))

    model.add(Conv2D(128,(3,3), padding='same')) …
Run Code Online (Sandbox Code Playgroud)

super deep-learning keras tensorflow

5
推荐指数
1
解决办法
4525
查看次数

调用 super().__init__() 在被覆盖时给出了错误的方法

我有一个基类和一个子类。在基类中,我有一个实例方法,它在__init__. 在子类中,我覆盖了这个方法。将super()在子类调用不会调用原始基本方法,但重写的子类的方法。为什么?

class BaseClass:
    def __init__(self, value):

        self.value = value
        self.transformed_value = self.create_value(value)

    def create_value(self, value):

        print("base")
        return value + 1

class SubClass(BaseClass):
    def __init__(self, value):

        super().__init__(value)

    def create_value(self, value):
        print("sub")
        return value + 2

s = SubClass(3)
Run Code Online (Sandbox Code Playgroud)

我希望打印输出是“基本”,但实际输出是“子”。我如何修改代码即可获得“基地”没有显式调用BaseClass.create_value(self, value)__init__BaseClass

python inheritance super

5
推荐指数
1
解决办法
471
查看次数

为什么 PyTorch 自定义模块中需要超级构造函数?

为什么super(LR, self).__init__()需要在下面的代码中调用?否则我会收到错误“AttributeError: cannot assign module before Module.init () call”。该错误是由self.linear = nn.Linear(input_size, output_size).

我不明白调用super(LR, self).__init__()和能够将 nn.Linear 对象分配给 self.linear之间有什么联系。nn.Linear 是一个单独的对象,它可以分配给任何类之外的变量,那么为什么super(LR, self).__init__()需要调用将 Linear 对象分配给类内的 self.linear 呢?

class LR(nn.Module):
    
    # Constructor
    def __init__(self, input_size, output_size):
        
        # Inherit from parent
        super(LR, self).__init__()
        self.test = 1
        self.linear = nn.Linear(input_size, output_size)
        
    
    # Prediction function
    def forward(self, x):
        out = self.linear(x)
        return out
Run Code Online (Sandbox Code Playgroud)

python inheritance super pytorch

5
推荐指数
2
解决办法
1586
查看次数