class People: def init(self, name, age): self.name = name self.age = age class Boyfriend(People): def init(self, name, age): super().init(name, age) class Girlfriend(People): def init(self, name, age): super().init(name, age)
时间: 2023-03-30 10:03:16 浏览: 93
这是一个关于 Python 类的问题,我可以回答。这段代码定义了一个 People 类,它有一个构造函数 init,接受两个参数 name 和 age,并将它们分别赋值给类的属性 self.name 和 self.age。此外,还定义了两个子类 Boyfriend 和 Girlfriend,它们都继承了 People 类,并重写了 init 方法,调用了父类的 init 方法。
相关问题
class Student(Person): def __init__(self, college, name, age, sex): super().__init__(name, age, sex) self.college=college self.class=class def personInfo(self): super().personInfo() print("学院:",self.college,
class Student(Person):
def __init__(self, college, name, age, sex, class_name):
super().__init__(name, age, sex)
self.college = college
self.class_name = class_name
def studentInfo(self):
print("姓名:", self.name, "年龄:", self.age, "性别:", self.sex, "学院:", self.college, "班级:", self.class_name)
def personInfo(self):
super().personInfo()
print("学院:", self.college, "班级:", self.class_name)
# 示例调用
s1 = Student("清华大学", "张三", 20, "男", "计算机科学与技术1班")
s1.personInfo()
s1.studentInfo()
自定义people类,要求如下: 1.有两个属性:姓名(name)和年龄(age) 2.有1个自定义方法,方法名为:Intro,作用是打印“name is age old.” 3.(以自己的名字和年龄)实例化一个对象,并调用自定的Intro方法。如:name为zhangsan,age为18,则调用Intro方法后打印为: zhangsan is 18 old.
好的,请看以下代码实现:
```python
class People:
def __init__(self, name, age):
self.name = name
self.age = age
def Intro(self):
print(self.name + " is " + str(self.age) + " old.")
# 实例化一个对象
person = People("Lily", 25)
# 调用自定义的Intro方法
person.Intro()
```
输出结果为:Lily is 25 old.
阅读全文