标签: super

Ruby 中的“super”是什么?

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

ruby super

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

在 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
查看次数

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
查看次数

Python3,从自定义异常中调用super的__init__

我已经在 python 3 中创建了自定义异常,并且所有代码都工作得很好。但有一件事我无法理解,为什么我需要将消息发送到 Exception 类的__init__()以及当我尝试打印异常时它如何将自定义异常转换为该字符串消息因为 Exception 甚至 BaseException 中的代码没有做太多事情。

不太明白为什么从自定义异常中调用super().__init__()

python exception super python-3.x

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

React Native - 超级表达式必须为 null 或函数

我想构建一个包含多个方法的超类,因为我想从不同的类中调用它们。此外,我还有减少代码的好处。

但是,我收到错误消息“超级表达式必须为空或函数”

这是我想要super.interface()从 SuperScreen.js 文件调用函数的类之一:

import React from "react";
import { SuperScreen } from "./SuperScreen";

export default class HomeScreen extends SuperScreen {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      data: null,
      key: 15
    };
  }

render() {
    return super.interface();
  }
}
Run Code Online (Sandbox Code Playgroud)

我的 SuperScreen.js

import React, { Component } from "react";

export default class SuperScreen extends Component {
  constructor() {}

  interface() {...}
}
Run Code Online (Sandbox Code Playgroud)

不过,我还是收到了消息Super expression must either be null or a function。为什么以及如何解决它?

亲切的问候和谢谢

javascript super superclass reactjs react-native

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

tkinter 应用程序中的 super()

我无法理解这个错误。

在下面的代码中,当我使用时,tk.Frame一切都按预期工作。但是,如果我使用super(),我会抛出一个AttributeError(“应用程序对象没有属性 tk ”)。

class Application(tk.Frame):
   def __init__(self,parent):
       tk.Frame.__init__(self,parent) <----- This works
       # super().__init__(self,parent) <------ This line throws an error
.
.
.

if __name__=='main':
  root=tk.Tk()
  Application(root).pack()
  root.mainloop()
Run Code Online (Sandbox Code Playgroud)

据我了解,super(Application,self).__init__()将调用绑定__init__到实例 MRO 中的类的方法child,即tkinter.Frame我的情况下的类。

我通过打印Application.__mro__和检查来验证这一点。

所以我的问题是,如果 和super().__init__(self,parent)tk.Frame.__init__(self,parent)引用相同的__init__class 方法tkinter.Frame,为什么一个会抛出错误,而另一个会正常工作?我怀疑我对 super() 的工作方式有一些误解。

class tkinter super python-3.x

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

为什么super无法访问python中类中的属性?

我有个问题。在使用 python 的 oops 中, super 可以访问方法或构造函数,但不能访问属性。这是为什么??

class Phone:

  def __init__(self, price, brand, camera):
    print ("Inside phone constructor")
    self.__price = price
    self.brand = brand
    self.camera = camera

def buy(self):
    print ("Buying a phone")

def return_phone(self):
    print ("Returning a phone")

class FeaturePhone(Phone):
    pass

class SmartPhone(Phone):
    def __init__(self, price, brand, camera, os, ram):
       super().__init__(price, brand, camera)
       self.os = os
      self.ram = ram
      print ("Inside smartphone constructor")

    def buy(self):
      print(super().camera) #Error
      print ("Buying a smartphone")

s=SmartPhone(20000, "Samsung", 12, "Android", 2)

print(s.buy()) #error
print(s.brand) …
Run Code Online (Sandbox Code Playgroud)

oop super python-3.x

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

调用 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
查看次数

Python MRO - super 在多重继承中的使用

我有这段代码,其中使用了超级继承和多重继承。班级成绩是:

go A go!
go C go!
go B go!
go D go!
Run Code Online (Sandbox Code Playgroud)

虽然我期望:

go A go!
go B go!
go D go!
Run Code Online (Sandbox Code Playgroud)

根据我的理解:D因为MRO调用了B类,因为go是在B中实现的。B类调用了它的父A的super。A被执行了,那就可以了。然后我期望 B 继续执行,所以这意味着 B 被执行,最后 D 被执行。但这当然是不正确的。为什么会进入C,因为go方法的定义是在B中找到的,那么它不应该再在C中搜索。这就是MRO的工作原理。它在头等舱中找到,不应该再搜索。完全困惑:(

 class A(object):
        def go(self):
            print("go A go!")

class B(A):
    def go(self):
        super(B, self).go()
        print("go B go!")

class C(A):
    def go(self):
        super(C, self).go()
        print("go C go!")

class D(B,C):
    def go(self):
        super(D, self).go()
        print("go D go!")

a = A()
b = B()
c = C()
d = D()

d.go()
Run Code Online (Sandbox Code Playgroud)

python super method-resolution-order python-3.x

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

为什么 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
查看次数