在python中,后台类和对象由字典表示,当您为字典中的键分配新值时,它会覆盖字典中的旧值。在
结果,当你写下:def testMethod(self, c):
它在字典中创建一个项,其键是testMethod,其值是一个带有2个参数的函数对象。在
当你写下:
^{pr2}$
它为键testMethod分配一个不同的值,即一个带有3个参数的函数对象。在
当你写下:
^{3}$
在类字典中查找testMethod键,该值是一个接受3个参数的函数对象。在Additionally, If both classes have 'init', and When I create instance
of MelonChart, only MelonChart 'init' is called.
是的,子类的__init__()方法重写父类的__init__()方法——就像greet()方法在下面的代码中所做的一样:import java.io.*;
class Animal {
public void greet(String greeting) {
System.out.print("An Animal wishes you: ");
System.out.println(greeting);
}
}
class Dog extends Animal {
public void greet(String greeting) {
System.out.print("A Dog barks out: ");
System.out.println(greeting);
}
}
public class MyProg {
public static void main(String[] args) {
Dog d = new Dog();
d.greet("hello");
}
}
--output:--
A Dog barks out: hello
对于作为构造函数的方法,Java有不同的规则(和语法),这不是很奇怪吗?在If only 'Chart' class has 'init', and when I create instance of
MelonChart, only parent's 'init' is called.
这就是继承的工作原理:当基类中找不到该方法时,python会在继承链上寻找父类中的__init__()方法。在As a previous Java Programmer, I can not understand why constructor of
parent doesn't have to be called...
在python中,如果您的子类定义了一个__init__()方法,那么您必须手动调用父类的构造函数:super().__init__()
下面是一个例子:class Chart(object):
def __init__(self, x):
self.x = x
def testMethod(self, a):
print("a")
class MelonChart(Chart):
def __init__(self, x, y):
super().__init__(x)
self.y = y
chart = MelonChart(10, 20)
print(chart.x, chart.y)
--output:--
10 20
嘿,看看这个:没有看不见的秘密方法调用父类构造函数!Java害怕什么?出来到光里去。让我们直截了当地说吧,不是吗?在
最后,python缩进是4个空格,不是2个空格,不是5个空格。有4个空格。你可以使用你想要的任何缩进,但是如果你要在一个公共表单上发布,那么它是4个空格。强制性的。在