Python面向对象(Object Oriented Programming,简称OOP)是一种编程范式,采用将数据和方法绑定成一个对象来实现程序设计和代码重用的思想。
Python面向对象的三个基本要素是类、对象和方法。类是具有相似特性的一组对象的集合,它定义了对象的属性和方法。对象是类的一个实例,可以执行类中定义的方法。方法是描述对象行为的函数,在类中定义。
1. 定义类和对象
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print("My name is {0}, and I am {1} years old".format(self.name, self.age))
p = Person("Tom", 24)
p.speak()
注释:上面的代码定义了一个名为Person的类,它有一个构造方法__init__,用于初始化对象的name和age属性;还有一个名为speak的方法,用于输出对象的姓名和年龄信息。代码中还创建了一个Person类的实例p,并调用它的speak方法。
2. 继承
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
pass
class Dog(Animal):
def speak(self):
print("I am {0}, and I am a dog".format(self.name))
class Cat(Animal):
def speak(self):
print("I am {0}, and I am a cat".format(self.name))
d = Dog("Wangcai", 3)
c = Cat("Kitty", 2)
d.speak()
c.speak()
注释:上面的代码定义了一个Animal类,它有一个构造方法__init__,用于初始化对象的name和age属性,并定义了一个speak方法;然后定义了两个子类Dog和Cat,它们继承自Animal类并覆盖了speak方法。代码中还创建了一个Dog类的实例d和Cat类的实例c,并调用它们的speak方法。
3. 多态
class Shape:
def calculate_area(self):
pass
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def calculate_area(self):
return self.length * self.width
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return 3.14 * self.radius ** 2
shapes = [Rectangle(3, 4), Circle(5)]
for shape in shapes:
print(shape.calculate_area())
注释:上面的代码定义了一个Shape类和两个子类Rectangle和Circle,它们都继承自Shape类并覆盖了calculate_area方法。代码中创建了一个包含两个不同类型对象(即一个Rectangle实例和一个Circle实例)的列表shapes,并使用它们各自的calculate_area方法计算面积。
4. 封装
class Bank:
def __init__(self):
self.__balance = 0
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if self.__balance >= amount:
self.__balance -= amount
return True
else:
return False
def get_balance(self):
return self.__balance
b = Bank()
b.deposit(1000)
b.withdraw(500)
print("Balance:", b.get_balance())
注释:上面的代码定义了一个Bank类,它有一个私有属性__balance,和三个公有方法deposit、withdraw和get_balance。在deposit和withdraw方法中,用到了self.__balance,这使得__balance属性不能被外部访问。代码中创建了一个Bank类的实例b,并对其进行存款和取款操作,最后输出余额信息。
5. 属性
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@property
def info(self):
return "{0} is {1} years old".format(self.name, self.age)
@info.setter
def info(self, value):
name, age = value.split()
self.name = name
self.age = int(age)
p = Person("Tom", 24)
print(p.info)
p.info = "Jerry 25"
print(p.info)
注释:上面的代码定义了一个Person类,它有一个构造方法__init__,和一个名为info的属性,使用了@property和@info.setter装饰器。在info的getter方法中返回一个字符串,表示对象的姓名和年龄。在setter方法中,使用value参数解析出新的姓名和年龄,并修改对象的属性。代码中创建了一个Person类的实例p,并输出其初始信息,然后用新的信息修改其属性,并输出修改后的信息。