在show方法里定义Father类的匿名子类,重写father类的method方法
时间: 2023-06-24 10:03:08 浏览: 54
好的,下面是示例代码:
```python
class Father:
def method(self):
print("This is Father's method.")
def show(self):
# 定义Father类的匿名子类
child = type('Child', (Father,), {
# 重写Father类的method方法
'method': lambda self: print("This is Child's method.")
})()
child.method()
father = Father()
father.show() # 输出 This is Child's method.
```
在`show`方法中,我们使用了`type`内置函数来动态创建一个类,该类继承自`Father`类,重写了`method`方法。然后我们创建了该类的一个实例`child`,并调用了它的`method`方法,从而输出了"This is Child's method."
相关问题
Java实现在show方法里定义Father类的匿名子类,重写father类的method方法
可以使用以下代码实现:
```java
public class Father {
public void method() {
System.out.println("Father's method");
}
public void show() {
Father anonymous = new Father() {
@Override
public void method() {
System.out.println("Anonymous subclass's method");
}
};
anonymous.method();
}
}
```
在 `show` 方法里,我们定义了一个 `Father` 类的匿名子类 `anonymous`,并重写了其 `method` 方法,然后调用了 `anonymous` 的 `method` 方法。当调用 `show` 方法时,输出结果为:
```
Anonymous subclass's method
```
试定义Animal类,编写sleep方法和show方法
以下是 Python 的代码实现:
```python
class Animal:
def __init__(self, name):
self.name = name
def sleep(self):
print(f"{self.name} is sleeping.")
def show(self):
print(f"I am a {type(self).__name__} and my name is {self.name}.")
```
这段代码定义了一个 `Animal` 类,其中包含了 `sleep()` 和 `show()` 方法。`__init__()` 方法用于初始化 `Animal` 类的实例,`name` 参数表示动物的名字。`sleep()` 方法用于模拟动物的睡眠行为,`show()` 方法用于展示动物的信息。在 `show()` 方法中,使用了 `type(self).__name__` 来获取当前实例的类名,这样可以避免在子类中重复编写类名。