原文: https://www.programiz.com/python-programming/object-oriented-programming
在本教程中,您将借助示例来学习 Python 中的面向对象编程(OOP)及其基本概念。
面向对象编程
Python 是一种多范式编程语言。 它支持不同的编程方法。
解决编程问题的一种流行方法是创建对象。 这就是所谓的面向对象编程(OOP)。
对象具有两个特征:
- 属性
- 行为
让我们举个例子:
鹦鹉可以是一个对象,因为它具有以下属性:
- 名称,年龄,颜色作为属性
- 唱歌,跳舞作为行为
Python 中的 OOP 概念专注于创建可重用的代码。 此概念也称为 DRY(不要重复自己)。
在 Python 中,OOP 的概念遵循一些基本原则:
类
类是对象的蓝图。
我们可以将类看作是带有标签的鹦鹉的素描。 它包含有关名称,颜色,大小等的所有详细信息。基于这些描述,我们可以研究鹦鹉。 在这里,鹦鹉是一个对象。
鹦鹉类的示例可以是:
class Parrot:pass
在这里,我们使用class关键字定义一个空类Parrot。 从类中,我们构造实例。 实例是从特定类创建的特定对象。
对象
对象(实例)是类的实例。 定义类时,仅定义对象的描述。 因此,没有分配内存或存储。
鹦鹉类对象的示例可以是:
obj = Parrot()
在此,obj是类别Parrot的对象。
假设我们有鹦鹉的详细信息。 现在,我们将展示如何构建鹦鹉的类和对象。
示例 1:在 Python 中创建类和对象
class Parrot:# class attributespecies = "bird"# instance attributedef __init__(self, name, age):self.name = nameself.age = age# instantiate the Parrot classblu = Parrot("Blu", 10)woo = Parrot("Woo", 15)# access the class attributesprint("Blu is a {}".format(blu.__class__.species))print("Woo is also a {}".format(woo.__class__.species))# access the instance attributesprint("{} is {} years old".format( blu.name, blu.age))print("{} is {} years old".format( woo.name, woo.age))
输出
Blu is a birdWoo is also a birdBlu is 10 years oldWoo is 15 years old
在上面的程序中,我们创建了一个名为Parrot的类。 然后,我们定义属性。 属性是对象的特征。
这些属性在类的__init__方法中定义。 创建对象后,首先运行的是初始化方法。
然后,我们创建Parrot类的实例。 这里,Blu和woo是我们新对象(值)的引用。
我们可以使用__class__.species访问class属性。 类的所有实例的类属性都相同。 同样,我们使用blu.name和blu.age访问实例属性。 但是,类的每个实例的实例属性都不同。
要了解有关类和对象的更多信息,请转到 Python 类和对象
方法
方法是在类主体内定义的函数。 它们用于定义对象的行为。
示例 2:在 Python 中创建方法
class Parrot:# instance attributesdef __init__(self, name, age):self.name = nameself.age = age# instance methoddef sing(self, song):return "{} sings {}".format(self.name, song)def dance(self):return "{} is now dancing".format(self.name)# instantiate the objectblu = Parrot("Blu", 10)# call our instance methodsprint(blu.sing("'Happy'"))print(blu.dance())
输出:
Blu sings 'Happy'Blu is now dancing
在上面的程序中,我们定义了两种方法,即sing()和dance()。 这些称为实例方法,因为它们是在实例对象(即blu)上调用的。
继承
继承是一种创建新类以使用现有类的详细信息而不进行修改的方法。 新形成的类是派生类(或子类)。 同样,现有类是基类(或父类)。
示例 3:在 Python 中使用继承
# parent classclass Bird:def __init__(self):print("Bird is ready")def whoisThis(self):print("Bird")def swim(self):print("Swim faster")# child classclass Penguin(Bird):def __init__(self):# call super() functionsuper().__init__()print("Penguin is ready")def whoisThis(self):print("Penguin")def run(self):print("Run faster")peggy = Penguin()peggy.whoisThis()peggy.swim()peggy.run()
输出:
Bird is readyPenguin is readyPenguinSwim fasterRun faster
在以上程序中,我们创建了两个类,即Bird(父类)和Penguin(子类)。 子类继承父类的功能。 我们可以从swim()方法中看到这一点。
再次,子类修改了父类的行为。 我们可以从whoisThis()方法中看到这一点。 此外,我们通过创建新的run()方法来扩展父类的功能。
另外,我们在__init__()方法内使用super()函数。 这使我们可以在子类中运行父类的__init__()方法。
封装形式
在 Python 中使用 OOP,我们可以限制对方法和变量的访问。 这样可以防止数据直接修改(称为封装)。 在 Python 中,我们使用下划线作为前缀来表示私有属性,即单_或双__。
示例 4:Python 中的数据封装
class Computer:def __init__(self):self.__maxprice = 900def sell(self):print("Selling Price: {}".format(self.__maxprice))def setMaxPrice(self, price):self.__maxprice = pricec = Computer()c.sell()# change the pricec.__maxprice = 1000c.sell()# using setter functionc.setMaxPrice(1000)c.sell()
输出:
Selling Price: 900Selling Price: 900Selling Price: 1000
在上面的程序中,我们定义了Computer类。
我们使用__init__()方法存储Computer的最高售价。 我们试图修改价格。 但是,我们无法更改它,因为 Python 将__maxprice视为私有属性。
如图所示,要更改该值,我们必须使用设置器函数,即setMaxPrice(),该函数将价格作为参数。
多态
多态是一种功能(在 OOP 中),可以将公共接口用于多种形式(数据类型)。
假设我们需要为形状着色,有多个形状选项(矩形,正方形,圆形)。 但是,我们可以使用相同的方法为任何形状着色。 这个概念称为多态。
示例 5:在 Python 中使用多态
class Parrot:def fly(self):print("Parrot can fly")def swim(self):print("Parrot can't swim")class Penguin:def fly(self):print("Penguin can't fly")def swim(self):print("Penguin can swim")# common interfacedef flying_test(bird):bird.fly()#instantiate objectsblu = Parrot()peggy = Penguin()# passing the objectflying_test(blu)flying_test(peggy)
输出:
Parrot can flyPenguin can't fly
在上面的程序中,我们定义了两个类别Parrot和Penguin。 它们每个都有一个通用的fly()方法。 但是,它们的功能不同。
要使用多态,我们创建了一个通用接口,即flying_test()函数,该函数接受任何对象并调用该对象的fly()方法。 因此,当我们在flying_test()函数中传递blu和peggy对象时,它有效地运行了。
要记住的要点:
- 面向对象的编程使程序易于理解并且高效。
- 由于该类是可共享的,因此可以重用该代码。
- 数据通过数据抽象是安全的。
- 多态允许相同的接口用于不同的对象,因此程序员可以编写高效的代码。
