本文介绍了TypeError:在for循环中创建类实例时,无法将“int”对象隐式转换为str的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到的错误TypeError:不能转换'int'对象隐式地str当使用for循环来创建类的实例。我是相当新的编程,并没有看到这个错误之前

  class Player(object):
properties = []
def __init __(self,name,wealth, player_number):
self.name = name
self.wealth = wealth
self.player_number = player_number
def __repr __(self):
return str(self.wealth )

玩家= {}

在范围内(0,Player_count):
players [player_+ x] = Player(input(Name ),input(Starting Wealth),x)

达到x

解决方案



  players [player_+ str(x)] =玩家(输入(Name),输入(Starting Wealth),x)

或使用字符串格式:

  players [player _ {}。format(x)] = Player(input(Name ),input(Starting Wealth),x)

code> player _ )和一个整数( 0 Player_count )被 x 引用。


I 'm getting the error "TypeError: Can't convert 'int' object to str implicitly" when using a for loop to create class instances.I'm fairly new to programming and haven't seen this error before

class Player(object):
    properties = []
    def __init__( self, name, wealth, player_number):
        self.name = name
        self.wealth = wealth
        self.player_number = player_number
    def __repr__(self):
        return str(self.wealth)

players = {}

for x in range(0, Player_count):
    players["player_" + x] = Player(input("Name"), input("Starting Wealth"), x)

I'm getting the error when it reaches x

解决方案

Turn the integer to a string explicitly then:

 players["player_" + str(x)] = Player(input("Name"), input("Starting Wealth"), x)

or use string formatting:

 players["player_{}".format(x)] = Player(input("Name"), input("Starting Wealth"), x)

You cannot just concatenate a string (player_) and an integer (the number between 0 and Player_count) referenced by x.

这篇关于TypeError:在for循环中创建类实例时,无法将“int”对象隐式转换为str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 08:57