class Dog(object): def __init__(self,name): self.name=name def play(self): print('%s 蹦蹦跳跳的玩'%self.name) class Person(object): def __init__(self,name): self.name=name #补充代码1:编写函数train,输出内容:张三正在训练大黄 def main(): #补充代码2:创建Dog对象,传递参数:"大黄" #补充代码3:创建Person对象,传递参数:"张三" #补充代码4:Person对象调用train函数操作Dog对象 if __name__=='__main__': main()
时间: 2024-02-22 07:00:58 浏览: 127
补充代码1:
```
def train(self, dog):
print('%s 正在训练%s' % (self.name, dog.name))
```
补充代码2:
```
dog = Dog("大黄")
```
补充代码3:
```
person = Person("张三")
```
补充代码4:
```
person.train(dog)
```
完整代码如下:
```
class Dog(object):
def __init__(self, name):
self.name = name
def play(self):
print('%s 蹦蹦跳跳的玩' % self.name)
class Person(object):
def __init__(self, name):
self.name = name
def train(self, dog):
print('%s 正在训练%s' % (self.name, dog.name))
def main():
dog = Dog("大黄")
person = Person("张三")
person.train(dog)
if __name__ == '__main__':
main()
```
相关问题
class PhoneDirectory: def __init__(self): self.tel_hash = {} self.name_hash = {}如何用链表表达
在Python中,`tel_hash` 和 `name_hash` 是两个字典,用于存储电话号码(键)和对应的名字(值)。如果你想使用链表来表示这些数据结构,我们需要转换为双向链表,因为字典本质上已经是哈希表,提供了非常快的查找性能。但在链表中,插入、删除操作可能会慢一些。
首先,定义一个节点类(Node)来构建链表:
```python
class Node:
def __init__(self, tel, name=None):
self.tel = tel
self.name = name
self.prev = None
self.next = None
class LinkedListPhoneDirectory:
def __init__(self):
self.head = None
self.tail = None
# 插入方法
def insert(self, tel, name):
if not self.head:
self.head = Node(tel, name)
self.tail = self.head
else:
new_node = Node(tel, name)
self.tail.next = new_node
new_node.prev = self.tail
self.tail = new_node
# 查找方法(这里只简单地遍历链表)
def find_by_tel(self, tel):
current = self.head
while current and current.tel != tel:
current = current.next
return current
# 示例
phone_directory = LinkedListPhoneDirectory()
phone_directory.insert("123", "Alice")
```
在这个实现中,`LinkedListPhoneDirectory` 类有一个头节点 `head` 和尾节点 `tail`,分别代表链表的开始和结束。`insert` 方法用于在链表末尾添加新条目,`find_by_tel` 方法用于根据电话号码查找对应的节点。
class Person: def __init__(self, name, age): self.name = name self.age = age
def introduce(self):
print(f"My name is {self.name} and I am {self.age} years old.")
class Student(Person):
def __init__(self, name, age, major):
super().__init__(name, age)
self.major = major
def study(self):
print(f"I am studying {self.major}.")
class Teacher(Person):
def __init__(self, name, age, subject):
super().__init__(name, age)
self.subject = subject
def teach(self):
print(f"I am teaching {self.subject}.")
s = Student("John", 20, "Computer Science")
s.introduce() # Output: My name is John and I am 20 years old.
s.study() # Output: I am studying Computer Science.
t = Teacher("Jane", 35, "Math")
t.introduce() # Output: My name is Jane and I am 35 years old.
t.teach() # Output: I am teaching Math.
阅读全文