请给出本科阶段学习Python的类的相关知识点,并举例
时间: 2023-07-16 21:12:09 浏览: 94
本科阶段学习Python的类的相关知识点包括:
1. 类的定义和实例化:学习如何定义类和创建类的实例对象。
示例代码:
```
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print("Hello, my name is {} and I am {} years old.".format(self.name, self.age))
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
person1.say_hello() # 输出 "Hello, my name is Alice and I am 25 years old."
person2.say_hello() # 输出 "Hello, my name is Bob and I am 30 years old."
```
2. 类的继承:学习如何使用继承来创建一个新的类,该类从另一个类继承属性和方法。
示例代码:
```
class Student(Person):
def __init__(self, name, age, major):
super().__init__(name, age)
self.major = major
def say_hello(self):
super().say_hello()
print("I am studying {}.".format(self.major))
student1 = Student("Charlie", 20, "Computer Science")
student1.say_hello() # 输出 "Hello, my name is Charlie and I am 20 years old. I am studying Computer Science."
```
3. 类的属性和方法:学习如何在类中定义属性和方法,并使用它们来操作类的实例对象。
示例代码:
```
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
rect1 = Rectangle(5, 10)
print(rect1.area()) # 输出 50
print(rect1.perimeter()) # 输出 30
```
4. 类的特殊方法:学习如何定义特殊方法,例如 `__str__` 和 `__eq__`,用于自定义类的字符串表示和相等性比较。
示例代码:
```
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "({}, {})".format(self.x, self.y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
point1 = Point(1, 2)
point2 = Point(3, 4)
point3 = Point(1, 2)
print(point1) # 输出 "(1, 2)"
print(point1 == point2) # 输出 False
print(point1 == point3) # 输出 True
```
阅读全文