Python:如何从超类创建子类?

96

在 Python 中,如何从一个超类创建一个子类?


4
请注意,Python已更改了子类化的方式,因此有两种方法可以实现,它们不能混合使用。如果混用会出错。阅读此文章以了解区别:https://dev59.com/EXI-5IYBdhLWcg3wta7w - Mark Lakata
13个回答

1
Python中的子类化如下所示:
class WindowElement:
    def print(self):
        pass

class Button(WindowElement):
    def print(self):
        pass

这里有一个关于Python的教程,其中还包含类和子类。


0

@thompsongunner答案进行了微小的补充。

要将参数传递给超类(父类),只需使用父类的函数签名即可:

class MySubClassBetter(MySuperClass):
    def __init__(self, someArg, someKwarg="someKwarg"):
        super().__init__(someArg, someKwarg=someKwarg)

你正在调用父类的__init__()方法,就像你构造任何其他类一样,这就是为什么你不需要包含self的原因。


0

这是一小段代码:

# create a parent class

class Person(object):
    def __init__(self):
        pass

    def getclass(self):
        return 'I am a Person'
# create two subclass from Parent_class

class Student(Person):
    def __init__(self):
        super(Student, self).__init__()

    def getclass(self):
        return 'I am a student'


class Teacher(Person):
    def __init__(self):
        super(Teacher, self).__init__()

    def getclass(self):
        return 'I am a teacher'


person1 = Person()
print(person1.getclass())

student1 = Student()
print(student1.getclass())

teacher1 = Teacher()
print(teacher1.getclass())

展示结果:

I am a Person
I am a student
I am a teacher

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接