我是靠谱客的博主 阔达哈密瓜,最近开发中收集的这篇文章主要介绍python循环中创建新对象_Python-在具有独立处理的循环中创建对象实例,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

您可以将实例存储在列表中:

politicians = []

for name in 'ABC':

politicians.append(Politician(name))

现在您可以访问各个实例:

>>> politicians[0].name

'A'

我使用了类的修改版本,如果没有提供,则为每个政治家提供默认年龄:

class Politician:

def __init__(self, name, age=45):

self.name = str(name)

self.age = age

self.votes = 0

def change(self):

self.votes = self.votes + 1

def __str__(self):

return self.name + ": " + str(self.votes)

现在,您可以使用您的政治家名单:

print('The Number of politicians: {}'.format(len(politicians)))

打印:

The Number of politicians: 3

这个:

for politician in politicians:

print(politician)

打印:

A: 0

B: 0

C: 0

分配随机投票:

import random

for x in range(100):

pol = random.choice(politicians)

pol.votes += 1

现在:

for politician in politicians:

print(politician)

打印:

A: 35

B: 37

C: 28

整个计划:

# Assuming Python 3.

class Politician:

def __init__(self, name, age=45):

self.name = str(name)

self.age = age

self.votes = 0

def change(self):

self.votes = self.votes + 1

def __str__(self):

return '{}: {} votes'.format(self.name, self.votes)

num_politicians = int(input("The number of politicians: "))

politicians = []

for n in range(num_politicians):

if n == 0:

new_name = input("Please enter a name: ")

else:

new_name = input("Please enter another name: ")

politicians.append(Politician(new_name))

print('The Number of politicians: {}'.format(len(politicians)))

for politician in politicians:

print(politician)

print('Processing ...')

for x in range(100):

pol = random.choice(politicians)

pol.votes += 1

for politician in politicians:

print(politician)

用法:

The number of politicians: 3

Please enter a name: John

Please enter another name: Joseph

Please enter another name: Mary

The Number of politicians: 3

John: 0 votes

Joseph: 0 votes

Mary: 0 votes

Processing ...

John: 25 votes

Joseph: 39 votes

Mary: 36 votes

UPDATE

正如@martineau建议的那样,对于真实存在的问题,字典会更多

有用.

创建字典而不是列表:

politicians = {}

在循环中,当您添加实例时,我们将名称作为键:

politicians[new_name] = Politician(new_name)

最后

以上就是阔达哈密瓜为你收集整理的python循环中创建新对象_Python-在具有独立处理的循环中创建对象实例的全部内容,希望文章能够帮你解决python循环中创建新对象_Python-在具有独立处理的循环中创建对象实例所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部