面对对象编程

本文介绍了Python中面向对象编程的基础概念,包括构造函数`__init__`用于初始化对象,身份标识`is`和`is not`用于判断对象是否相同,方法如`deposit`和`withdraw`的使用,以及类的属性和实例属性的差异。通过实例展示了如何创建和操作对象,以及类变量和实例变量的影响。
摘要由CSDN通过智能技术生成

1. 构造函数(__ init_ _)

Python中用来初始化对象的方法有一个特殊的名称:_ _ init _ _。这个方法也被叫做类的构造函数(constructor)。

>>> class Account:
		def __init__(self, account_holder):
			self.balance = 0
			self.holder = account_holder

_ _ int_ _方法有两个参数:__self__绑定到新创建的Account对象上,accounter_holder绑定到实例化时传入的参数上。
实例化:

>>> a = Account('Anna')

实例化调用Account创建了一个新的对象,是Account的实例。

>>> a.balance
0
>>> a.holder
'Anna'

2. 身份(Indentity)

每个新建账户都有自己的属性,属性的值都和其他账户独立。

>>> b = Account('Bob')
>>> b.balance = 200
>>> [acc.balance for acc in (a, b)]
[0, 200]

检查身份是不是同一个用“is"和“is not”:

>>> a is a
True
>>> a is not b
True
>>> c = a
>>> c is a
True

3. 方法(Methods)

对象的方法是类中定义的函数,如下的deposit和withdraw函数都是Account这个类的实例的方法。

>>> class Account:
        def __init__(self, account_holder):
            self.balance = 0
            self.holder = account_holder
        def deposit(self, amount):
            self.balance = self.balance + amount
            return self.balance
        def withdraw(self, amount):
            if amount > self.balance:
                return 'Insufficient funds'
            self.balance = self.balance - amount
            return self.balance    

当方法被调用的时候,会发生两件事:1. 确定方法是干什么的,方法名不是个变量名,而是类中的一个函数;2. 将self绑定给调用该方法的对象。

>>> Bob_account.deposit(100)
100
>>> Bob_account.withdraw(90)
10
>>> Bob_account.withdraw(90)
'Insufficient funds'
>>> Bob_account.holder
'Spock'

4. 函数和方法的区别

>>> type(Account.deposit)
<class 'function'>
>>> type(spock_account.deposit)
<class 'method'>

由上面的代码可以看出,第一个是标准的函数,有两个参数self和amount。第二个则是方法,self自动绑定给spock_account。

5. 类的属性

类的属性是在类中,在方法之外的赋值语句,也被成为类变量或是静态变量。

>>> class Account:
        interest = 0.02            # A class attribute
        def __init__(self, account_holder):
            self.balance = 0
            self.holder = account_holder
        # Additional methods would be defined here

如果类中的属性变了,则类所有的实例的属性也会跟着变化。

>>> Account.interest = 0.04
>>> spock_account.interest
0.04
>>> kirk_account.interest
0.04
>>> kirk_account.interest = 0.08
>>> Account.interest = 0.05  # changing the class attribut
>>> spock_account.interest     # changes instances without like-named instance attributes
0.05
>>> kirk_account.interest     # but the existing instance attribute is unaffected
0.08
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值