简体   繁体   English

如何最好地打印从用户定义的实例变量创建的字典?

[英]How to best print dictionaries created from user defined instance variables?

I am trying to organize my cows into a dictionary, access their values, and print them to the console.我正在尝试将我的奶牛组织成字典,访问它们的值并将它们打印到控制台。

Each instance of a cow is assigned to an index in list cow.牛的每个实例都分配给牛列表中的一个索引。

I am attempting to create a dictionary as follows:我正在尝试按如下方式创建字典:

for i in cows:
    cowDict[i.getName] = (i.getWeight, i.getAge)

I'd like to be able to access the values of my dictionary using my cows names, ie:我希望能够使用我的奶牛名称访问我的字典的值,即:

c["maggie"]

however, my code produces a key error.但是,我的代码会产生一个关键错误。

If I print the entire dictionary, I get something to this effect:如果我打印整个字典,我会得到这样的效果:

"{<'bound method cow.getName of <'maggie, 3, 1>>: (<'bound method cow.getWeight of <'maggie, 3, 1>>, <'bound method cow.getAge of <'maggie, 3, 1>>), etc... }" "{<'绑定方法cow.getName of <'maggie, 3, 1>>: (<'绑定方法cow.getWeight of <'maggie, 3, 1>>, <'绑定方法cow.getAge of <'maggie , 3, 1>>),等等... }"

I can replace.getName with the instance variable and get the desired result, however, I've been advised away from that approach.我可以用实例变量替换.getName 并获得所需的结果,但是,有人建议我不要使用这种方法。

What is best practice to create a dictionary using instance variables of type cow?使用牛类型的实例变量创建字典的最佳实践是什么?

Code:代码:

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 is a function so try getName 是 function 所以试试

for i in cows:
    cowDict[i.getName()] = (i.getWeight(), i.getAge())

You can simplify this with something like:您可以通过以下方式简化此操作:

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])

Which outputs:哪个输出:

<maggie, 3, 1>
<mooderton, 6, 2>
<miles, 10, 3>
<mickey, 5, 4>
<steve, 3, 5>
<margret, 8, 6>
<steph, 12, 7>

This looks like a job for zip .这看起来像是zip的工作。 We can use it in conjunction with dict comprehensions to create dictionaries from arbitrary key and value expressions as follows我们可以将它与字典推导结合使用,从任意键和值表达式创建字典,如下所示

{name: (weight, age) for name, weight, age in zip(names, weights, ages)}`

We can then redefine buildCows as然后我们可以将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 has an open door policy on class attributes, so they are by default public unless, their names are preceded by underscores or double underscores (dunders). Python 对 class 属性有一个开放的政策,因此默认情况下它们是公共的,除非它们的名称前面有下划线或双下划线(dunders)。 It is generally unnecessary to create getters/accessor methods, as you would in many other OO-languages.通常不需要像在许多其他 OO 语言中那样创建 getter/accessor 方法。 If you really do want private instance variables you can read up on them here如果你真的想要私有实例变量,你可以在这里阅读它们

The reason for the erroneous results in the dict, was that it was being populated with references to the functions instead of calling them (ie i.getWeight should have been `i.getWeight() dict 中错误结果的原因是它被填充了对函数的引用而不是调用它们(即i.getWeight应该是 `i.getWeight()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM