如何最好地打印从用户定义的实例变量创建的字典?
How to best print dictionaries created from user defined instance variables?
我正在尝试将我的奶牛整理到字典中,访问它们的值,并将它们打印到控制台。
奶牛的每个实例都分配给奶牛列表中的一个索引。
我正在尝试创建一个字典如下:
for i in cows:
cowDict[i.getName] = (i.getWeight, i.getAge)
我希望能够使用我的牛名访问我的字典的值,即:
c["maggie"]
但是,我的代码产生了一个关键错误。
如果我打印整本词典,我会得到这样的结果:
"{<'绑定方法cow.getName of <'maggie, 3, 1>>: (<'绑定方法cow.getWeight of <'maggie, 3, 1>>, <' <'maggie, 3, 1>> 的绑定方法 cow.getAge), etc...}"
我可以用实例变量替换 .getName 并获得所需的结果,但是,有人建议我不要使用这种方法。
使用 cow 类型的实例变量创建字典的最佳做法是什么?
代码:
class cow(object):
""" A class that defines the instance objects name, weight and age associated
with cows
"""
def __init__(self, name, weight, age):
self.name = name
self.weight = weight
self.age = age
def getName(self):
return self.name
def getWeight(self):
return self.weight
def getAge(self):
return self.age
def __repr__(self):
result = '<' + self.name + ', ' + str(self.weight) + ', ' + str(self.age) + '>'
return result
def buildCows():
"""
this function returns a dictionary of cows
"""
names = ['maggie', 'mooderton', 'miles', 'mickey', 'steve', 'margret', 'steph']
weights = [3,6,10,5,3,8,12]
ages = [1,2,3,4,5,6,7]
cows = []
cowDict = {}
for i in range(len(names)):
#creates a list cow, where each index of list cow is an instance
#of the cow class
cows.append(cow(names[i],weights[i],ages[i]))
for i in cows:
#creates a dictionary from the cow list with the cow name as the key
#and the weight and age as values stored in a tuple
cowDict[i.getName] = (i.getWeight, i.getAge)
#returns a dictionary
return cowDict
c = buildCows()
getName 是一个函数所以尝试
for i in cows:
cowDict[i.getName()] = (i.getWeight(), i.getAge())
你可以用类似的东西来简化它:
names = ['maggie', 'mooderton', 'miles', 'mickey', 'steve', 'margret', 'steph']
weights = [3,6,10,5,3,8,12]
ages = [1,2,3,4,5,6,7]
cows = {names[i]: (weights[i], ages[i]) for i in range(len(names))}
for name in names:
print '<%s, %d, %d>' % (name, cows[name][0], cows[name][1])
输出:
<maggie, 3, 1>
<mooderton, 6, 2>
<miles, 10, 3>
<mickey, 5, 4>
<steve, 3, 5>
<margret, 8, 6>
<steph, 12, 7>
这看起来像是 zip 的工作。我们可以将它与字典推导结合使用,从任意键和值表达式创建字典,如下所示
{name: (weight, age) for name, weight, age in zip(names, weights, ages)}`
然后我们可以将 buildCows
重新定义为
def buildCows():
names = ['maggie', 'mooderton', 'miles', 'mickey', 'steve', 'margret', 'steph']
weights = [3,6,10,5,3,8,12]
ages = [1,2,3,4,5,6,7]
return {name: (weight, age) for name, weight, age in zip(names, weights, ages)}
Python 对 class 属性采取开放政策,因此默认情况下它们是 public,除非它们的名称前面有下划线或双下划线(双下划线)。通常不需要像在许多其他 OO 语言中那样创建 getters/accessor 方法。如果你真的想要私有实例变量,你可以阅读它们 here
dict 中错误结果的原因是它被填充了对函数的引用而不是调用它们(即 i.getWeight
应该是 `i.getWeight()
我正在尝试将我的奶牛整理到字典中,访问它们的值,并将它们打印到控制台。
奶牛的每个实例都分配给奶牛列表中的一个索引。
我正在尝试创建一个字典如下:
for i in cows:
cowDict[i.getName] = (i.getWeight, i.getAge)
我希望能够使用我的牛名访问我的字典的值,即:
c["maggie"]
但是,我的代码产生了一个关键错误。
如果我打印整本词典,我会得到这样的结果:
"{<'绑定方法cow.getName of <'maggie, 3, 1>>: (<'绑定方法cow.getWeight of <'maggie, 3, 1>>, <' <'maggie, 3, 1>> 的绑定方法 cow.getAge), etc...}"
我可以用实例变量替换 .getName 并获得所需的结果,但是,有人建议我不要使用这种方法。
使用 cow 类型的实例变量创建字典的最佳做法是什么?
代码:
class cow(object):
""" A class that defines the instance objects name, weight and age associated
with cows
"""
def __init__(self, name, weight, age):
self.name = name
self.weight = weight
self.age = age
def getName(self):
return self.name
def getWeight(self):
return self.weight
def getAge(self):
return self.age
def __repr__(self):
result = '<' + self.name + ', ' + str(self.weight) + ', ' + str(self.age) + '>'
return result
def buildCows():
"""
this function returns a dictionary of cows
"""
names = ['maggie', 'mooderton', 'miles', 'mickey', 'steve', 'margret', 'steph']
weights = [3,6,10,5,3,8,12]
ages = [1,2,3,4,5,6,7]
cows = []
cowDict = {}
for i in range(len(names)):
#creates a list cow, where each index of list cow is an instance
#of the cow class
cows.append(cow(names[i],weights[i],ages[i]))
for i in cows:
#creates a dictionary from the cow list with the cow name as the key
#and the weight and age as values stored in a tuple
cowDict[i.getName] = (i.getWeight, i.getAge)
#returns a dictionary
return cowDict
c = buildCows()
getName 是一个函数所以尝试
for i in cows:
cowDict[i.getName()] = (i.getWeight(), i.getAge())
你可以用类似的东西来简化它:
names = ['maggie', 'mooderton', 'miles', 'mickey', 'steve', 'margret', 'steph']
weights = [3,6,10,5,3,8,12]
ages = [1,2,3,4,5,6,7]
cows = {names[i]: (weights[i], ages[i]) for i in range(len(names))}
for name in names:
print '<%s, %d, %d>' % (name, cows[name][0], cows[name][1])
输出:
<maggie, 3, 1>
<mooderton, 6, 2>
<miles, 10, 3>
<mickey, 5, 4>
<steve, 3, 5>
<margret, 8, 6>
<steph, 12, 7>
这看起来像是 zip 的工作。我们可以将它与字典推导结合使用,从任意键和值表达式创建字典,如下所示
{name: (weight, age) for name, weight, age in zip(names, weights, ages)}`
然后我们可以将 buildCows
重新定义为
def buildCows():
names = ['maggie', 'mooderton', 'miles', 'mickey', 'steve', 'margret', 'steph']
weights = [3,6,10,5,3,8,12]
ages = [1,2,3,4,5,6,7]
return {name: (weight, age) for name, weight, age in zip(names, weights, ages)}
Python 对 class 属性采取开放政策,因此默认情况下它们是 public,除非它们的名称前面有下划线或双下划线(双下划线)。通常不需要像在许多其他 OO 语言中那样创建 getters/accessor 方法。如果你真的想要私有实例变量,你可以阅读它们 here
dict 中错误结果的原因是它被填充了对函数的引用而不是调用它们(即 i.getWeight
应该是 `i.getWeight()