标签: super

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

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

方法解析顺序 (MRO) 在此 Python 代码中如何工作

class parent:
    def __init__(self):
        self.a=2
        self.b=4
    def form1(self): 
        print("calling parent from1")
        print('p',self.a+self.b)
 
class child1(parent):
    def __init__(self):
        self.a=50
        self.b=4
    def form1(self):
        print('bye',self.a-self.b)
    def callchildform1(self):
        print("calling parent from child1")
        super().form1()
 
class child2(parent):
    def __init__(self):
        self.a=3
        self.b=4
    def form1(self):
        print('hi',self.a*self.b)
    def callchildform1(self):
        print("calling parent from child2")
        super().form1()
 
class grandchild(child1,child2):
    def __init__(self):
        self.a=10
        self.b=4
    def callingparent(self):
        super().form1()
 
g=grandchild()
g.callchildform1()
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,当我调用 时g.callchildform1(),根据 MRO 规则,将首先在同一个类中搜索该方法,然后是第一个父级(此处为 child1),然后是第二个父级(child2)。正如预期的那样,它调用child1.callchildform1()并执行第一行print("calling parent from child1")super().form1()但在此之后,我预计将执行下一行,该行将被调用parent.form1(),但这种情况不会发生。相反,child2.form1()正在被调用。请解释一下为什么会出现这种情况?

python oop multiple-inheritance super

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

pub 和 pub(super) 何时具有不同的语义?

Rust 支持pubpub(super)pub使得父模块可以访问一个项目......并且pub(super)似乎也做了完全相同的事情。我尝试过使用下面的示例,并进行交换pubpub(super)似乎没有效果:

#![allow(dead_code)]

mod outer {
    pub(super) fn outer_foo() { inner::inner_foo(); }
    mod inner {
        pub(super) fn inner_foo() { println!("hello world!"); }
    }
}

fn top_level_foo() { outer::outer_foo(); }
Run Code Online (Sandbox Code Playgroud)

为什么你会使用其中一种而不是另一种?

游乐场链接。

encapsulation module super rust

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

Python多重继承中调用双亲的构造函数(一般情况)

我试图弄清楚Python中的多重继承,但我找到的所有文章都仅限于简单的情况。让我们考虑以下示例:

class Vehicle:
    def __init__(self, name: str) -> None:
        self.name = name
        print(f'Creating a Vehicle: {name}')

    def __del__(self):
        print(f'Deleting a Vehicle: {self.name}')


class Car(Vehicle):
    def __init__(self, name: str, n_wheels: int) -> None:
        super().__init__(name)
        self.wheels = n_wheels
        print(f'Creating a Car: {name}')

    def __del__(self):
        print(f'Deleting a Car: {self.name}')


class Boat(Vehicle):
    def __init__(self, name: str, n_props: int) -> None:
        super().__init__(name)
        self.propellers = n_props
        print(f'Creating a Boat: {name}')

    def __del__(self):
        print(f'Deleting a Boat: {self.name}')


class Amfibii(Car, Boat):
    def __init__(self, name: str, n_wheels: int, n_props: …
Run Code Online (Sandbox Code Playgroud)

python inheritance super diamond-problem

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

我需要调用[super viewDidUnload]吗?

我已经看到一些苹果公司的例子可以打电话,[super viewDidUnload];而另一些则没有.我读了一篇文章(几个月前,所以我不记得那个网址),说这[super viewDidUnload];是不必要的,但除此之外没有解释.

有没有明确的理由为什么或为什么不告诉超级的viewDidUnload
并且,(如果应该这样做)在将所有属性设置为nil,之后或之前是否重要之前,我是否应该调用super ?

- (void)viewDidUnload {
    // Is this necessary?
    // [super viewDidUnload];

    self.tableDataSource = nil;
    self.titleLabel = nil;

    // Is it better to call super before or after nil'ing properties?
    // [super viewDidUnload];
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

objective-c super ios viewdidunload

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

Scala重载了构造函数和超级

我无法理解如何在Java上开发类似于以下内容的Scala代码:

public abstract class A {
   protected A() { ... }
   protected A(int a) { ... }
}

public abstract class B {
   protected B() { super(); }
   protected B(int a) { super(a); }
}

public class C extends B {
   public C() { super(3); }
}
Run Code Online (Sandbox Code Playgroud)

虽然很清楚如何开发C类,但我无法获得如何接受B.帮助.

PS我正在尝试创建自己的基于wicket WebPage的BaseWebPage,这是Java的常见做法

constructor scala super constructor-overloading

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

在一个表达式中将ArrayList <String>转换为String []?

我有一个构造函数接受一个ArrayList<String>,但想调用super期望一个String[]数组.

我尝试过以下内容,但会导致类异常, [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

public cool(ArrayList<String> s) {
    super((String[]) s.toArray());
}
Run Code Online (Sandbox Code Playgroud)

我希望能够通过cool一个ArrayList<String>

谢谢

编辑:我已经尝试了最近使用的建议

super(s.toArray(new String[s.size()]));
Run Code Online (Sandbox Code Playgroud)

但现在我得到以下异常:

entity must have a no-arg constructor.; nested exception is java.lang.IllegalArgumentException: : entity must have a no-arg constructor.

java casting exception super

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

Python - 如何正确设置类的层次结构?

我有以下代码:

class Computer(object):
    def __init__(self, name):
        self.name = name

class CPU(Computer):
    def __init__(self):
        super(CPU, self).__init__(name)
        self.name = name

mycomputer = Computer('My Computer')
mycomputer.CPU.name = 'Intel'

print mycomputer.name, mycomputer.CPU.name
Run Code Online (Sandbox Code Playgroud)

我想得到以下内容:

My Computer, Intel
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

AttributeError: 'Computer' object has no attribute 'CPU'    
Run Code Online (Sandbox Code Playgroud)

如何正确设置类,所以一旦我运行主代码,我会得到我需要的东西?我甚至不确定我是否正确使用super().

我非常感谢你的帮助.

python class subclass super

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

与具有__init __()的super()有关的问题

鉴于以下3个课程,

class A(object):
    def __init__(self):
        print('A')
    def test(self):
        print('1')

class B(A):
    def __init__(self):
        super(B,self)        ## if .__init__() is not given here
        print('B')

class C(B, A):
    def __init__(self):
        super(C, self).__init__()
        print('C')
Run Code Online (Sandbox Code Playgroud)

如果我跑步D = C(),它将返回

B
C
Run Code Online (Sandbox Code Playgroud)

如果我跑步print(C.__mro__),它会给予帮助(<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>)。我认为这意味着将在列表中执行A类,但是mro事实并非如此。

我想问为什么.__init__()A.__init__()发生这种情况。

python super

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