类与对象中的属性赋值

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

如上图定义了一个账户类,利息设置为0.02,在此类上实例化两个对象,其默认利息都是0.02

>>> spock_account = Account('Spock')
>>> kirk_account = Account('Kirk')
>>> spock_account.interest
0.02
>>> kirk_account.interest
0.02

若我们在类中对interest进行更改,则在此类上实例化的所有对象都会做出相应的更改

>>> Account.interest = 0.04
>>> spock_account.interest
0.04
>>> kirk_account.interest
0.04

 若想更改某实例化对象中的interest值,采用<expression> . <name>(表达式会优先查找<expression>对象中的<name>属性,若在对象中找不到,则会寻找类中的<name>属性)方式进行更改,如:

>>> kirk_account.interest = 0.08

此表达式会在kirk_acount对象中新建一个interest属性,并赋值为0.08,这种赋值不会改变类中的属性,其他对象中的interest不会改变

>>> kirk_account.interest
0.08
>>> spock_account.interest
0.04

若在此基础上更改类中的interest属性,kirk_acount中的interest并不会改变,因为kirk_acount中的interest是新建的同名属性

>>> Account.interest = 0.05  # changing the class attribute
>>> spock_account.interest     # changes instances without like-named instance attributes
0.05
>>> kirk_account.interest     # but the existing instance attribute is unaffected
0.08

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值