如何从' self'中获取保存的值?语法,使用变量作为'键'?
部分代码:
<body>
<div id="container" style="width: 75%;">
<canvas id="canvas"></canvas>
</div>
<script>
weekdays=["Monday", "Tuesday", "Wednesday", "Thurday", "Friday", "Saturday", "Sunday", "Monday"]
var d=new Date()
var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var randomScalingFactor = function() {
return (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100);
};
var barChartData = {
labels: [weekdays[d.getDay()], weekdays[d.getDay()-6], weekdays[d.getDay()-5], weekdays[d.getDay()-4], weekdays[d.getDay()-3], weekdays[d.getDay()-2],weekdays[d.getDay()-1] ],
datasets: [{
label: 'Logged Time',
backgroundColor: "rgba(220,220,220,0.5)",
data: sessions
}
]
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
// Elements options apply to all of the options unless overridden in a dataset
// In this case, we are setting the border of each bar to be 2px wide and green
elements: {
rectangle: {
borderWidth: 2,
borderColor: 'rgb(0, 255, 0)',
borderSkipped: 'bottom'
}
},
responsive: true,
title: {
display: true,
text: 'Vision Logged Hours'
}
}
});
};
</script>
我无法执行切换声明,因为我有21个值......
为了使其更清晰,如果class Foo:
def __init__(self, n1, n2, n3, ...):
self.node_1 = n1
self.node_2 = n2
self.node_3 = n3
...
def get_node(n):
return self."node_"+n # This is wrong. What should I use?
,我想要值n = 2
。因此self.node_2
为n = 3
等,
答案 0 :(得分:5)
您可以使用getattr(class_obj, 'property')
。在传递类的对象和属性以作为function ClickSkin(id)
{
// Get the div and set the div orange
var selected_div = document.getElementById("pic"+id);
selected_div.style.backgroundColor = 'orange';
for(var i = 0; i < 310; i++)
{
if(document.getElementById("pic"+i))
{
if(i != id)
{
document.getElementById("pic"+i).style.backgroundColor='white';
}
}
}
}
访问时,您将获得相应属性的值。以下是示例代码:
string
但是,您还应该将class MyClass:
def __init__(self, n1, n2):
self.node_1 = n1
self.node_2 = n2
def get_node(self, n):
return getattr(self, n)
x = MyClass('value_1', 'value_2')
print x.get_node('node_1')
# Output: 'value_1'
方法更新为使用__init__()
,因为您提到了大量的属性。使用setattr(class_obj, 'property', value)
和enumerate()
动态设置属性。下面是一个例子:
**args