python中的类,对象和列表

时间:2015-03-26 11:28:22

标签: python class

所以我试图创建一个程序,但我仍然遇到课程困难。该程序(当然没有完成)将打印一个随机数量的村庄。每个村庄(第二类)将有一个随机数目的氏族(第一类)。无论如何,我的问题是村级。我如何确保将区域和家庭规模添加到Village类?如何将Clan类中的计数器插入Village类?正如你所看到的那样,当我将一些氏族随机化时,这些区域和家庭规模应该加入到Village类中。我该怎么办?我的乡村班有什么问题?

class Clan:
 counter = 0

 def __init__(self):
    r = random.randrange(20, 101)
    self.area = r
    s = random.randrange(1, 6)
    self.familySize = s
    Clan.counter += 1
    self.counter = Clan.counter

 def getArea(self):
    return self.area

 def getFamilySize(self):
    return self.familySize


class Village:
 counter = 0

 def __init__(self):
    self.clan_list = []
    for i in range(random.randrange(3, 7)): 
        self.clan_list += [Clan()]
 def getclan_list(self):
    return self.clan_list
 def getArea(self):
    return self.area
 def getPopulation(self):
    pass

2 个答案:

答案 0 :(得分:1)

由于面积和总体的值取决于clan_list中的氏族,因此每次需要时都应计算这些值。替代方案要复杂得多 - 必须控制如何在村庄中添加和移除部族如何改变部落的面积和家庭规模,并在村庄中反映这些变化。< / p>

以下是如何计算村庄面积和人口的示例。第一个使用getter方法,第二个使用更多python-esque属性。

import random

class Clan:
    counter = 0

    def __init__(self):
        r = random.randrange(20, 101)
        self.area = r
        s = random.randrange(1, 6)
        self.familySize = s
        Clan.counter += 1
        self.counter = Clan.counter

    # removed getters
    # Unless your getter or setter is doing something special,
    # just access the attribute directly.



class Village:

    def __init__(self):
        self.clan_list = []
        for i in range(random.randrange(3, 7)): 
            self.clan_list.append(Clan())

    # for a village, area is a computed value, so use a getter
    def getArea(self):
        total_area = 0
        for clan in self.clan_list:
            total_area += clan.area
        return total_area

    # the prefered alternative to getters (and setters) are properties
    # note that the function is named as if it was an attribute rather than function
    @property
    def population(self):
        # use sum and generator rather than a for loop
        return sum(clan.familySize for clan in self.clan_list)


# How to use a village instance
v = Village()
# get area
print("area:", v.getArea())
# get population
print("population:", v.population)
# note how population is accessed as if it was an attribute rather than called 
# like a function

答案 1 :(得分:0)

那么,您希望村级人员计算村里有多少家庭?

families = 0
for clan in self.clan_list
    families += clan.getFamilySize()