class person(): def __init__(self,a,b): self.a = a self.b = b def sociality(self): print(a,b) class son(person): def __init__(self,a,b,c): person.__init__(self,a,b) self.c = c def virtu(self): print(c)这段代码有什么问题吗
时间: 2023-06-09 14:02:01 浏览: 61
这段代码没有语法错误,但是在son类中的virtu方法中打印变量c时应该使用self.c而不是c。正确的代码应该是:
```
class person():
def __init__(self,a,b):
self.a = a
self.b = b
def sociality(self):
print(self.a,self.b)
class son(person):
def __init__(self,a,b,c):
person.__init__(self,a,b)
self.c = c
def virtu(self):
print(self.c)
```
相关问题
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.
from objprint import op class Animal: def __init__(self,age): self.age = age class Person(Animal): def __init__(self, age,name): super().__init__(age) self.name = name class Male(Person): def __init__(self, age, name): super(Person,self).__init__(age) self.gender = "male" m = Male(32,"Peter") super(Male,m).__init__(32,"Peter") op(m)
这段代码也存在语法错误。在Male类中,应该使用super().__init__(age, name)来调用父类Person的构造函数,而不是使用super(Person, self).__init__(age)。同时,在Male类中,应该先调用父类的构造函数,然后再添加gender属性,否则会出现AttributeError异常。在修正这些问题之后,代码应该如下所示:
```python
from objprint import op
class Animal:
def __init__(self, age):
self.age = age
class Person(Animal):
def __init__(self, age, name):
super().__init__(age)
self.name = name
class Male(Person):
def __init__(self, age, name):
super().__init__(age, name)
self.gender = "male"
m = Male(32, "Peter")
super(Male, m).__init__(32, "Peter")
op(m)
```
这样,代码就不会出现语法错误,并且能够正常运行。注意,这里在最后一行代码中使用了op(m)来输出对象m的属性和方法,需要确保已经安装了objprint模块才能够使用op函数。