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