为什么类中的方法操作__init__变量

时间:2018-03-05 03:27:30

标签: python class

我有这个课程Record

class Record():
    def __init__(self, record):
        self.state_abbreviations = {'AL': 'Alabama'}
        self.raw_record = record
        self.is_valid = self.validate_record(self.raw_record)
        self.formatted_record = self.format_record(self.raw_record)


    def validate_record(self, record):
        if (record.get('provider_first_name') is None and 
            record.get('provider_last_name_legal_name') is None):
            return False
        return True

    def format_record(self, record):
        # swap state abbreviation for full state name
        record_state = record.get('provider_business_practice_location_address_state_name')
        full_state_name = self.state_abbreviations.get(record_state)
        record['provider_business_practice_location_address_state_name'] = full_state_name

        return record

当我实例化它时:

r = Record({'provider_first_name': 'is', 'provider_last_name_legal_name': 'fake',
            'provider_business_practice_location_address_state_name': 'AL'})

我希望r.raw_record能给我

{'provider_business_practice_location_address_state_name': 'AL',
 'provider_first_name': 'is',
 'provider_last_name_legal_name': 'fake'}

但我得到的输出是:

{'provider_business_practice_location_address_state_name': 'Alabama',
 'provider_first_name': 'is',
 'provider_last_name_legal_name': 'fake'}

我对为什么原始记录被format_record函数操纵感到困惑。

1 个答案:

答案 0 :(得分:1)

Record正在引用您传递给self.raw_record构造函数的字典,然后将其传递给format_record方法并在那里进行修改。在您操作相同对象的所有这些部分中,这就是您在raw_record中看到更改的原因。

如果你想避免这种情况,可以在某处复制字典。例如,在构造函数中:

self.formatted_record = self.format_record(self.raw_record.copy())