类与对象中的属性赋值
1 class Account: 2 interest = 0.02 # A class attribute 3 def __init__(self, account_holder): 4 self.balance = 0 5 self.holder = account_holder 6 # 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_account.interest 0.08 >>> spock_account.interest 0.04
此表达式会在kirk_acount对象中新建一个interest属性,并赋值为0.08,这种赋值不会改变类中的属性,其他对象中的interest不会改变,若在此基础上更改类中的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
浙公网安备 33010602011771号