geekdoc-python-zh/docs/pythonguru/019.md

3.5 KiB
Raw Permalink Blame History

Python 对象和类

原文: https://thepythonguru.com/python-object-and-classes/


于 2020 年 1 月 7 日更新


创建对象和类


Python 是一种面向对象的语言。 在 python 中,所有东西都是对象,即intstrbool甚至模块,函数也是对象。

面向对象的编程使用对象来创建程序,这些对象存储数据和行为。

定义类


python 中的类名以class关键字开头,后跟冒号(:)。 类通常包含用于存储数据的数据字段和用于定义行为的方法。 python 中的每个类还包含一个称为初始化器的特殊方法(也称为构造器),该方法在每次创建新对象时自动被调用。

让我们来看一个例子。

class Person:

       # constructor or initializer
      def __init__(self, name): 
            self.name = name # name is data field also commonly known as instance variables

      # method which returns a string
     def whoami(self):
           return "You are " + self.name

在这里,我们创建了一个名为Person的类,其中包含一个名为name和方法whoami()的数据字段。

什么是self


python 中的所有方法(包括一些特殊方法,如初始化器)都具有第一个参数self。 此参数引用调用该方法的对象。 创建新对象时,会自动将__init__方法中的self参数设置为引用刚创建的对象。

从类创建对象


p1 = Person('tom') # now we have created a new person object p1
print(p1.whoami())
print(p1.name)

预期输出

You are tom
tom

注意

当您调用一个方法时,您无需将任何内容传递给self参数python 就会在后台自动为您完成此操作。

您也可以更改name数据字段。

p1.name = 'jerry'
print(p1.name)

预期输出

jerry

尽管在类之外授予对您的数据字段的访问权是一种不好的做法。 接下来,我们将讨论如何防止这种情况。

隐藏数据字段


要隐藏数据字段,您需要定义私有数据字段。 在 python 中,您可以使用两个前划线来创建私有数据字段。 您还可以使用两个下划线定义私有方法。

让我们看一个例子

class BankAccount:

     # constructor or initializer
    def __init__(self, name, money):
         self.__name = name
         self.__balance = money   # __balance is private now, so it is only accessible inside the class

    def deposit(self, money):
         self.__balance += money

    def withdraw(self, money):
         if self.__balance > money :
             self.__balance -= money
             return money
         else:
             return "Insufficient funds"

    def checkbalance(self):
         return self.__balance

b1 = BankAccount('tim', 400)
print(b1.withdraw(500))
b1.deposit(500)
print(b1.checkbalance())
print(b1.withdraw(800))
print(b1.checkbalance())

预期输出

Insufficient funds
900
800
100

让我们尝试访问类外部的__balance数据字段。

print(b1.__balance)

预期输出

AttributeError: 'BankAccount' object has no attribute '__balance'

如您所见,现在在类外部无法访问__balance字段。

在下一章中,我们将学习运算符重载