原文: https://pythonspot.com/objects-and-classes

介绍

技术总是在发展。什么是类,它们从何而来?

1. 语句:在计算的早期,程序员仅编写命令。

2. 函数:可重用的语句组,有助于结构化代码并提高了可读性。

3. 类:这些类用于创建具有功能和变量的对象。 字符串是对象的示例:字符串书具有功能book.replace()book.lowercase()。这种样式通常称为面向对象编程。

让我们一起深入吧!

Python 类

我们可以在 Python 中创建虚拟对象。 虚拟对象可以包含变量和方法。 程序可能具有许多不同的类型,并且是从类创建的。 例:

  1. class User:
  2. name = ""
  3. def __init__(self, name):
  4. self.name = name
  5. def sayHello(self):
  6. print("Hello, my name is " + self.name)
  7. # create virtual objects
  8. james = User("James")
  9. david = User("David")
  10. eric = User("Eric")
  11. # call methods owned by virtual objects
  12. james.sayHello()
  13. david.sayHello()

运行该程序。 在此代码中,我们有 3 个虚拟对象:jamesdavideric。 每个对象都是User类的实例。

Python 类:对象和类 - 图1

Python 类:创建对象

在此类中,我们定义了sayHello()方法,这就是为什么我们可以为每个对象调用它的原因。__init__()方法被称为构造函数,并且在创建对象时始终被调用。该类拥有的变量在这种情况下为name。这些变量有时称为类属性。

我们可以在类中创建方法来更新对象的内部变量。这听起来可能有些含糊,但我将举一个例子进行说明。

类变量

我们定义了一个CoffeeMachine类,其中的虚拟对象包含大量的咖啡豆和大量的水。 两者都定义为数字(整数)。然后我们可以定义添加或删除豆子的方法。

  1. def addBean(self):
  2. self.bean = self.bean + 1
  3. def removeBean(self):
  4. self.bean = self.bean - 1

对于水,我们也是如此。如下所示:

  1. class CoffeeMachine:
  2. name = ""
  3. beans = 0
  4. water = 0
  5. def __init__(self, name, beans, water):
  6. self.name = name
  7. self.beans = beans
  8. self.water = water
  9. def addBean(self):
  10. self.beans = self.beans + 1
  11. def removeBean(self):
  12. self.beans = self.beans - 1
  13. def addWater(self):
  14. self.water = self.water + 1
  15. def removeWater(self):
  16. self.water = self.water - 1
  17. def printState(self):
  18. print "Name = " + self.name
  19. print "Beans = " + str(self.beans)
  20. print "Water = " + str(self.water)
  21. pythonBean = CoffeeMachine("Python Bean", 83, 20)
  22. pythonBean.printState()
  23. print ""
  24. pythonBean.addBean()
  25. pythonBean.printState()

运行该程序。 代码的顶部定义了我们所描述的类。 下面的代码是我们创建虚拟对象的地方。 在此示例中,我们只有一个对象称为pythonBean。 然后我们调用更改内部变量的方法,这是可能的,因为我们在类中定义了这些方法。 输出:

  1. Name = Python Bean
  2. Beans = 83
  3. Water = 20
  4. Name = Python Bean
  5. Beans = 84
  6. Water = 20

下载练习