写出下列程序的运行结果:class A: def__init__(self): self.i=1 def m(self): self.i=10 class B(A): def m(self): self.i+=1 return self.i def main(): b=B() print(b.m()) main()
时间: 2024-03-05 15:52:48 浏览: 38
这段程序的运行结果是:
```
2
```
首先定义了一个父类 `A`,其中有一个构造方法 `__init__()`,用于初始化实例变量 `i`,将其赋值为 `1`。还有一个成员方法 `m()`,用于修改实例变量 `i` 的值,将其赋值为 `10`。
然后定义了一个子类 `B`,继承自父类 `A`。子类 `B` 重写了父类 `A` 的成员方法 `m()`,其中将实例变量 `i` 的值加 `1`,并返回其新值。
在 `main()` 函数中,创建了一个子类 `B` 的对象 `b`,然后调用了 `b` 的成员方法 `m()`,返回值为 `2`。这是因为 `i` 的初始值为 `1`,在 `m()` 方法中将其加 `1`,所以返回值为 `2`。
相关问题
写出下列程序的运行结果:class A: sef__init__(self,i=1): self.i=i class B(A): def__init__(self,j=2): super().__init__() self.j=j def main(): b=B() print(b.i,b.j) main()
这段代码也有一些语法错误,我先纠正一下:
```python
class A:
def __init__(self, i=1):
self.i = i
class B(A):
def __init__(self, j=2):
super().__init__()
self.j = j
def main():
b = B()
print(b.i, b.j)
main()
```
程序的运行结果是:
```
1 2
```
这是因为我们定义了两个类 `A` 和 `B`,其中 `B` 是 `A` 的子类。在 `B` 的构造函数中,我们先调用了 `super().__init__()`,这样就调用了父类 `A` 的构造函数,将 `self.i` 初始化为默认值 1。然后我们再将 `self.j` 初始化为参数 `j` 的值,默认值为 2。最后在 `main()` 函数中,我们创建一个 `B` 对象 `b`,输出它的 `i` 和 `j` 属性,分别为 1 和 2。
写出下列程序的运行结果:class A: def__new__(self): self.__init__(self) print("A's__new__()invoked") def__init__(self): print("A's__init__()invoked") class B(A): def__new__(self): print("B's__new__()invoked") def__init__(self): print("B's__init__()invoked") def main(): b=B() a=A() main()
这段程序存在语法错误,正确的写法应该是:
```python
class A:
def __new__(self):
self.__init__()
print("A's __new__() invoked")
def __init__(self):
print("A's __init__() invoked")
class B(A):
def __new__(self):
print("B's __new__() invoked")
def __init__(self):
print("B's __init__() invoked")
def main():
b = B()
a = A()
main()
```
程序的运行结果是:
```
B's __new__() invoked
B's __init__() invoked
A's __new__() invoked
A's __init__() invoked
```
首先创建了一个 `B` 类的实例 `b`,调用了 `B` 类的 `__new__()` 方法和 `__init__()` 方法。`B` 类的 `__new__()` 方法仅仅打印了一句话,`B` 类的 `__init__()` 方法打印了一句话。
接着创建了一个 `A` 类的实例 `a`,调用了 `A` 类的 `__new__()` 方法和 `__init__()` 方法。`A` 类的 `__new__()` 方法调用了 `__init__()` 方法,打印了一句话,然后自己打印了一句话。
因此,程序的输出结果是:
```
B's __new__() invoked
B's __init__() invoked
A's __new__() invoked
A's __init__() invoked
```