如何理解并解决Python面向对象编程问题
Python是一种动态类型、面向对象的编程语言。在面向对象编程中,主要问题包括类定义、对象创建、继承关系、多态应用等。
- 类定义:明确对象的属性和行为。例如:
```python
class Person:
def init(self, name):self.name = name
p = Person(‘Alice’)
2. 对象创建:根据类创建特定的对象。如上面的例子,`Person('Alice')`就创建了一个名为`Alice`的`Person`对象。
3. 继承关系:一个类可以继承另一个类的属性和方法。例如:
```python
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def bark(self):
return "Woof!"
my_dog = Dog('Rex', 'Bark!')
print(my_dog.bark()) # Output: Woof!
- 多态应用:在同一个继承链中,不同的子类对象对同一方法调用可以产生不同的结果。例如:
```python
class Shape:
def area(self):
pass
class Rectangle(Shape):
def init(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
class Triangle(Shape):
def init(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
shapes = [Rectangle(10, 5)), Triangle(3, 4)]
for shape in shapes:
print(shape.class.name, “: “, shape.area()) # Output:
还没有评论,来说两句吧...