Python是一种多范式的动态类型语言,它的面向对象编程能力是非常强大的。Python的类是实现面向对象编程的基本单元。
Python中的类可以包含属性和方法。属性就是类中的变量,而方法则是类中的函数。Python中的类和其他语言中的类有些不同,Python中的类不存在public和private关键字,因为Python中的属性和方法都默认是public的,也就是说,它们随时可以被实例化对象调用。除此之外,Python中的类还支持继承,可以使用继承来扩展现有的类。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print("Hi, My name is", self.name, "and I am", self.age, "years old.")
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def introduce(self):
super().introduce()
print("I am a student in grade", self.grade)
class Teacher(Person):
def __init__(self, name, age, subject):
super().__init__(name, age)
self.subject = subject
def introduce(self):
super().introduce()
print("I am a teacher of", self.subject)
student = Student("Tom", 14, 8)
teacher = Teacher("Jim", 35, "Math")
student.introduce()
teacher.introduce()上面是一个简单的类的例子。类名为Person,它有两个属性name和age,以及一个方法introduce,用于自我介绍。类Student继承自Person,并增加了一个属性grade,以及方法introduce,用于自我介绍,并且能显示它的年级。类Teacher也继承自Person,并增加了一个属性subject,以及方法introduce,用于自我介绍,并且能显示它的科目。
最后,我们实例化了一个学生和一个老师,并调用它们的introduce方法。我们可以看到,学生和老师都能进行自我介绍,并且这个自我介绍包含了它们自己特有的信息。
本文可能转载于网络公开资源,如果侵犯您的权益,请联系我们删除。
0
