我有以下课程:
class Group(object):
_name = ''
_link = ''
_collection = []我有以下功能:
def getSubGroups(url, groups):
group = groups[0]
#sleep(15)
html = requests.get(url+group.getLink())
content = BeautifulSoup(html.text, "lxml")
subGroup = None
#Retrieving groups and people listed above these groups
for div in content.find_all('div', {"class":["size14", "person-box"]}):
#Group
if "size14" in div.attrs['class']:
if subGroup != None:
#Adding a subgroup to its repective subgroup
group.addCollection(subGroup)
print 'NFL = ', group.getName()
print '2014...', subGroup.getName()
print 'List of groups', group.getCollection()
print 'List of persons', subGroup.getCollection()
break
subGroup = Group()
subGroup.setLink(div.a['href'])
subGroup.setName(div.text)
#Person
if "person-box" in div.attrs['class']:
divPerson = div.find('div', 'name')
person = Person()
person.setName(divPerson.text)
person.setLink(divPerson.a['href'])
#Adding a person to its repective group
subGroup.addCollection(person)
return group该打印给我的输出如下:
NFL = NFL Players
2014... 2014 NFL Draft Picks and Rookies
List of groups [<Person.Person object at 0x7fd79a4bff50>, <Person.Person object at
0x7fd79a4bff90>, ..., <Group.Group object at 0x7fd79a4bff10>]
List of persons [<Person.Person object at 0x7fd79a4bff50>, <Person.Person object at
0x7fd79a4bff90>, ..., <Person.Person object at 0x7fd79a454990>,
<Group.Group object at 0x7fd79a4bff10>]正如那些关注我的人所看到的,我正在运行一个测试,我本来希望有=>列表的组[<Group.Group object at 0x7ff54bb86350>],但是它也添加了所有的person对象。
为了测试我的理智,我创建了另一个名为Subgroup的类,现在它对我很好。但是,我仍然认为,在Java或C++中,我可以做到这一点。为什么我不能和蟒蛇在一起?我不想再创建一个完全相同的类!
发布于 2015-02-01 21:00:56
这可能是你的问题。
class Group(object):
_name = '' # <--- variables defined here belong
_link = '' # <--- to the class itself, not to
_collection = [] # <--- class instances.当您直接在该类下定义变量时,它们实际上是类变量(类似于Java或C++中的静态变量)。
当您打印您的集合时,请注意,在两行打印中,十六进制数是相同的。这很可能是因为group._collection和subGroup._collection引用相同的列表(Group._collection,在类级别上定义的列表)。这就是为什么您在列表中看到Person和Group的原因--您的子组正在向列表中添加Person对象,而您的组正在添加Group对象。
在python中,实例变量是在__init__函数中定义的(类似于Java/C++中的构造函数)。
我怀疑你想做这样的事
class Group(object):
def __init__(self):
self._name = '' # <--- variables defined here
self._link = '' # <--- belong to the instance only
self._collection = []然后,每次您说Group()时,您都将创建一个新的Group对象,该对象具有自己的列表_collection。
https://stackoverflow.com/questions/28267623
复制相似问题