如何遍历类对象并更改Python中的属性值

时间:2020-01-07 05:53:14

标签: python

我有以下两个类MasterProgramList和ProgramList。 MasterProgramList接受一个json数组对象,该对象在下面的用法代码中定义。 我试图遍历每个Program对象并更改start_date属性。 当我这样做时,该值不会更改,而是保持为json数组对象中定义的值。 我的ProgramList / Program类有问题吗?如何遍历类对象并更改属性值?

MasterProgramList.py

import json
import datetime
class MasterProgramList(object):
    def __init__(self, program_list, today=None):
        self.program_list = [ProgramList(program) for program in program_list]
        self.today = today

    def current_programs(self):
        if self.today is not None:
            def filter_if_between_start_and_end(program):
                return (datetime.datetime.strptime(program.start_date, '%Y-%m-%d').date()) <= self.today.date() <= (
                        datetime.datetime.strptime(program.end_date, '%Y-%m-%d').date())

                program_list = self.program_list
                for x in program_list:
                    x.programs = filter(filter_if_between_start_and_end, x.programs)

                filtered_program_list = program_list
            else:
                filtered_program_list = self.program_list
            return filtered_program_list

ProgramList.py

class ProgramList(object):
    """
    CRM-specific version of the ProgramList Configuration object
    """
    def __init__(self, config):
        self._config = config
        self.brand = config['brand']
        self.programs = self._parse_programs(config['brand'], config['programs'])

    def _parse_programs(cls, brand, program_list):
        return [Program.from_json(brand, p) for p in program_list]

class Program(object):
    def __init__(self, **kwargs):
        self._config = kwargs.get('config') #required json data
        self.name = kwargs.get('name') #required json data
        self.start_date = kwargs.get('start_date') #required json data
        self.end_date = kwargs.get('end_date') #required json data

    def __repr__(self):
        return str(self._config)

    @classmethod
    def from_json(cls, brand, program_json):
        program_json['name'] = '{0}_{1}'.format(brand.capitalize(), program_json['name'])
        program_json['department'] = 'CRM'
        return Program(
            config = program_json,
            name = program_json['name'],
            start_date = program_json['start_date'],
            end_date = program_json['end_date']
        )

用法:

from datetime import datetime, timedelta

crm_program_master_list = [
    {
        "brand": "testbrand",
        "programs": [
            {
                "name": "Program1",
                "start_date": "2020-01-02",
                "end_date": "2999-12-31"
            },
            {
                "name": "Program2",
                "start_date": "2020-01-04",
                "end_date": "2999-12-31"
            }
        ]
    }
]

today_date = (datetime.strptime('2020-01-06', '%Y-%m-%d'))
crm_programs_to_analyze = MasterProgramList(crm_program_master_list, today=today_date)
crm_programs_to_analyze.program_list = crm_programs_to_analyze.current_programs()

programs = []
for x in crm_programs_to_analyze.program_list:
    for p in x.programs:
        #change the start_date for each program
        p.start_date = '2020-01-22'
        print('program: {}'.format(p))
        programs.append(p)
output:
program: {'name': 'Program1', 'end_date': '2999-12-31', 'department': 'CRM', 'start_date': '2020-01-02'}
program: {'name': 'Program2', 'end_date': '2999-12-31', 'department': 'CRM', 'start_date': '2020-01-04'}

expected output:
program: {'name': 'Program1', 'end_date': '2999-12-31', 'department': 'CRM', 'start_date': '2020-01-22'}
program: {'name': 'Program2', 'end_date': '2999-12-31', 'department': 'CRM', 'start_date': '2020-01-22'}

2 个答案:

答案 0 :(得分:1)

首先,需要进行一些清理以使其正常工作:

在“用法”部分中,没有ProgramListMasterProgramList的导入。我将它们添加为:

from MasterProgramList import MasterProgramList
from ProgramList import ProgramList

然后,在MasterProgramList.py中,我导入了ProgramList

继续,我看到crm_programs_to_analyze.program_list是一个包含一个ProgramList.ProgramList对象的列表。因此,您的外部for循环对该单个对象进行了一次迭代。然后,内部for循环访问ProgramList程序的成员,并在其中将start_date设置为2020-01-22

您遇到的问题在于__repr__方法中-特别是在获取其返回值的位置。这是一个说明问题的非常简短的示例:

>>> class f:
...   def __init__(self, config):
...     self.config = config
...     self.start_date = config['start_date']
...     self.end_date = config['end_date']
...   def __repr__(self):
...     return str(self.config)
...
>>> conf = {'start_date': '2020-10-10', 'end_date': '2021-12-03'}
>>> foo = f(conf)
>>> foo
{'start_date': '2020-10-10', 'end_date': '2021-12-03'}
>>> foo.start_date = '2019-10-10' # <-- Changes start_date, but not config
>>> foo
{'start_date': '2020-10-10', 'end_date': '2021-12-03'} # <-- From config
>>> foo.start_date # <-- but this as updated as expected
'2019-10-10'
>>> foo.config
{'start_date': '2020-10-10', 'end_date': '2021-12-03'} # <-- unchanged
>>> foo.config['start_date'] = foo.start_date
>>> foo
{'start_date': '2019-10-10', 'end_date': '2021-12-03'}
>>> foo.start_date
'2019-10-10'
>>> foo.config # <-- now it's changed and they match
{'start_date': '2019-10-10', 'end_date': '2021-12-03'}

start_date 的值正在更新。但是通过p打印__repr__是从_config获取原始值,而修改p.start_date时不会更新原始值。要解决此问题,请添加更新以更改{{1}中的start_date,或让p._config返回__repr__的值。

赞:

start_date

答案 1 :(得分:1)

此代码存在多个问题。让我们处理第一个问题。

class MasterProgramList(object):
    def __init__(self, program_list, today=None):
        #ProgramList is a class, not a function.  It has no return value.  
        self.program_list = [ProgramList(program) for program in program_list]
        self.today = today

    #do not define function after conditional logic.  
    def filter_if_between_start_and_end(self, program):
        return (datetime.datetime.strptime(program.start_date, '%Y-%m-%d').date()) <= self.today.date() <= (
                    datetime.datetime.strptime(program.end_date, '%Y-%m-%d').date())

    def current_programs(self):
        if self.today is not None:
            program_list = self.program_list
            for x in program_list:
                x.programs = filter(self.filter_if_between_start_and_end(x.programs))

            filtered_program_list = program_list
        else:
            filtered_program_list = self.program_list
        return filtered_program_list