tyb*_*blu 0 python class instance
在放弃丑陋的bash脚本之后,我一直在学习如何在今天的大部分时间里使用Python.
我正在尝试使用2个类来定义一些对象数组,其中存储一些唯一的字符串和整数(1-10).对象将包括以下内容:
object[i].user
.n # n = i
.name
.coords
.hero
Run Code Online (Sandbox Code Playgroud)
(param1,param2,param3)对于每个object.n和object.user都是不同的,所以我在尝试使用一个在编写90个唯一字符串后看起来不像垃圾的赋值方法.嵌套我发现的例子不起作用,所以这里是妥协:
class CityBean:
def __init__(self,name,coords,hero):
self.name = name
self.coords = coords
self.hero = hero
class Castles:
def __init__(self,user,n):
self.user = user
self.n = n
if self.user == 'user1':
temp = {
1: CityBean( "name1" , "coord1" , "hero1"),
... blah blah blah
10: CityBean( "name10" , "coord10" , "hero10" )}[self.n]()
if self.user == 'user2':
temp = {
1: CityBean( "name11" , "coord11" , "hero11" ),
... blah blah blah
10: CityBean( "name20" , "coord20" , "hero20" ) }[self.n]()
if self.user == 'user3':
temp = {
1: CityBean( "name21" , "coord21" , "hero21" ),
... blah blah blah
10: CityBean( "name30" , "coord30" , "hero30" ) }[self.n]()
self.name = temp.name
self.coords = temp.coords
self.hero = temp.coords
__del__(temp)
Run Code Online (Sandbox Code Playgroud)
我称之为:
cities = list( Castles("user2",i) for i in range(1,11) )
Run Code Online (Sandbox Code Playgroud)
它给了我这个错误:
AttributeError: CityBean instance has no __call__ method
Run Code Online (Sandbox Code Playgroud)
它归咎于这一行:
10: CityBean( "name20" , "coord20" , "hero20" ) }[self.n]() # pseudo
10: CityBean( "" , "" , "" ) }[self.n]() # what is actually looks like
Run Code Online (Sandbox Code Playgroud)
我的邋classes班有什么问题?我做了一些迟钝的事,不是吗?
很难从你提供的内容中猜出你想要什么,因为你提供了新手代码,而不是说你想做什么,所以你的猜测时间很长.
我认为这样的事情会做:
data = {
(1, 'user1'): ("name1", "coord1", "hero1"),
(2, 'user1'): ("name2", "coord2", "hero2"),
#...
(1, 'user2'): ("name11", "coord11", "hero11"),
(2, 'user2'): ("name12", "coord12", "hero12"),
# ...
}
class CityBean:
def __init__(self,name,coords,hero):
self.name = name
self.coords = coords
self.hero = hero
class Castles:
def __init__(self,user,n):
self.user = user
self.n = n
name, coords, hero = data.get((n, user))
self.citybean = CityBean(name, coords, hero)
Run Code Online (Sandbox Code Playgroud)