使用另一个类变量的值填充类变量

时间:2014-10-07 22:42:22

标签: python json

我正在尝试从chart_title的内容中填充我的标题变量,如下所示:

class LineHighChart(object):
    chart_title = ''

    title = {'text':chart_title,
             'x':-20
             }

我通过以下方式在另一个方面这样做:

def weight_graph(request):
    highchart = LineHighChart()

    chart_title = 'my chart title'


    highchart.chart_title = chart_title

    print highchart.__dict__

    return JsonResponse(highchart.__dict__, safe=False)

这不包含已填充的title属性,而是打印:

{'chart_title': 'joe'}

我想要打印:

{'title': {'text':'my chart title',
             'x':-20
             }}

4 个答案:

答案 0 :(得分:0)

是的,LineHighChart中的标题字典不会自动更新,因为您更新了对象的另一个属性。如果要获得此行为,可以使用setter属性:

class LineHighChart(object):
    def __init__(self):
        self._chart_title = ''
        self.title = {'text': self._chart_title, 'x':-20}

    @property
    def chart_title(self):
        return self._chart_title

    @chart_title.setter
    def chart_title(self, value):
        self._chart_title = value
        self.title['text'] = value  

highchart = LineHighChart()
chart_title = 'my chart title'
highchart.chart_title = chart_title
print highchart.__dict__
# {'_chart_title': 'my chart title', 'title': {'text': 'my chart title', 'x': -20}}

我还将类变量(此类的所有实例共享的class.variable)更改为实例变量(self.variable),这样当您在一个对象中更新chart_title时,它不会影响其他同一个班级的实例。

答案 1 :(得分:0)

您定义了几个不会出现在实例__dict__

中的类级别变量
class LineHighChart(object):
    chart_title = ''
    title = {'text':chart_title,
             'x':-20
             }

然后,您定义了一个与类变量

同名的实例级变量
highchart = LineHighChart()
chart_title = 'my chart title'
highchart.chart_title = chart_title

尽管名称相同,但这两个变量存在于不同的名称空间中。当您对实例级名称空间进行json编码时,不会包含类级别的任何内容。

如果您想要实例级属性,请将它们包含在init

类中
class LineHighChart(object):

    def __init__(self):
        self.chart_title = ''
        self.title = {'text':self.chart_title,
             'x':-20
             }

但请注意,self.title['text']在将新值分配给self.chart_title时不会发生变化。

答案 2 :(得分:0)

由于标题涉及类变量......

class LineHighChart(object):
    chart_title = 'Class Variable'

    # using a property getter for the title, to be dynamic
    @property
    def title(self):
        # uses the class variable
        return {'text': LineHighChart.chart_title, 'x': -20}

    def __init__(self):
        # gets initialized and will not be changed
        self.title2 = {'text': self.chart_title, 'x': -20}

def weight_graph(request):
    highchart = LineHighChart()
    lowchart = LineHighChart()

    # setting a NEW object variable
    highchart.chart_title = 'new object variable value'

    # overriding the class variable
    LineHighChart.chart_title = 'new Class Variable'

    print('class variable:        {}'.format(LineHighChart.chart_title))

    # dict does not contain class variables
    print('highchart.__dict__:    {}'.format(highchart.__dict__))

    # get the NEW object variable!
    print('highchart.chart_title: {}'.format(highchart.chart_title))
    # title uses the class variable 
    print('highchart.title:       {}'.format(highchart.title))
    # title2 uses the 'old' class variable
    print('highchart.title2:      {}'.format(highchart.title2))

    # get the class variable, because no new object variable was set
    print('lowchart.chart_title:  {}'.format(lowchart.chart_title))
    # title uses the class variable 
    print('lowchart.title:        {}'.format(lowchart.title))
    # title2 uses the 'old' class variable
    print('lowchart.title2:       {}'.format(lowchart.title2))

weight_graph(None)

输出是:

class variable:        new Class Variable
highchart.__dict__:    {'title2': {'x': -20, 'text': 'Class Variable'}, 'chart_title': 'new object variable value'}

highchart.chart_title: new object variable value
highchart.title:       {'x': -20, 'text': 'new Class Variable'}
highchart.title2:      {'x': -20, 'text': 'Class Variable'}

lowchart.chart_title:  new Class Variable
lowchart.title:        {'x': -20, 'text': 'new Class Variable'}
lowchart.title2:       {'x': -20, 'text': 'Class Variable'}

答案 3 :(得分:0)

我认为更好地利用基于set setter值更改实例变量的方法是执行以下操作:

class LineHighChart(object):
    #title = {'text':' ', 'x':-20}


    def __init__(self, title, subtitle, x_axis_list, y_axis_title, metric, series):

        self.title = {'text': title, 'x':-20}

        self.subtitle =  {
            'text': subtitle,
            'x': -20
        }

        self.xAxis = {
            'categories': x_axis_list
        }

        self.yAxis = {
            'title': {
                'text':y_axis_title
            },
            'plotLines': [{
                'value': 0,
                'width': 1,
                'color': '#808080'
            }]
        }

        self.tooltip = {
            'valueSuffix': metric
        }

        self.legend = {
            'layout': 'vertical',
            'align': 'right',
            'verticalAlign': 'middle',
            'borderWidth': 0
        }

        self.series = series

然后将此类称为:

def weight_graph(request):
    print 'weight graph'
    x_axis_list = ['Day 1', 'Day 2', 'Day 3']
    series = [{
            'name': 'Tokyo',
            'data': [7.0, 1.0, 9.5]
        }, {
            'name': 'New York',
            'data': [-0.2, 0.8, 5.7]
        }]

    highchart = LineHighChart(
                              'my chart',
                              'last seven days',
                              x_axis_list,
                              'Weight',
                              ' lbs',
                              series
                              )

    return JsonResponse(highchart.__dict__, safe=False)