为什么键函数可以调用属性?但是我不能直接调用控制台中的属性?

2024-09-25 00:32:28 发布

您现在位置:Python中文网/ 问答频道 /正文

完整代码来自DEAP包示例:

https://github.com/DEAP/deap/blob/0ef6c40b4ba24dbbf1591bd97b08857a1fe3376a/examples/ga/onemax.pyHere

我做了一个测试,人口和个体的大小都是5,我输入了下面的语句:

>>>MAX=max(pop,key=attrgetter("fitness"))
>>>[1,1,1,1,1]

我知道这件事流行健身但是,为什么我不能直接称之为:

>>>pop.fitness

出现错误:

Traceback (most recent call last):

  File "<ipython-input-74-b9dde7c090eb>", line 1, in <module>
    pop.fitness

AttributeError: 'list' object has no attribute 'fitness'

为什么这个pop.fitness不能被调用?你知道吗


Tags: 代码httpsgithubcom示例popexamplesblob
1条回答
网友
1楼 · 发布于 2024-09-25 00:32:28

poplist/iterable。列表本身没有属性fitness。该列表包含每个对象都有一个属性fitnessattrgetter('fitness')创建一个函数,当用对象调用时,该函数返回该对象的fitness属性。max使用这个函数从列表中获取它应该排序的值。你知道吗

我不知道你的单子上到底有什么,但它是这样的:

>>> pop
[Thing(fitness=1), Thing(fitness=2), ...]

这两个是等价的:

>>> pop[0].fitness
1
>>> attrgetter('fitness')(pop[0])
1

max(pop, key=attrgetter('fitness'))是按照以下思路做的:

for thing in pop:
    thing.fitness  # here be magic using this property as sorting criterion

相关问题 更多 >