Форум сайта python.su
1
Ребят, нужна ваша помощь :
Есть класс , у которого есть 2 свойства
есть список
нужно при создании объекта добавить его в список, а потом в цикле вызвать метод этих объектов.
Офлайн
13
Офлайн
1
class State(object): def __init__ (self,country,capital): self.country = country self.capital = capital self.mas = [] def print_out(self) : print "The capital of",self.country,"is",self.capital obj1 = State("Russia","Moskow") obj1.print_out() print obj1.mas.append(obj1.country) obj1.mas.append(obj1.capital)
Офлайн
103
я не пойму что вы хотите сделать, но я бы сделал так
class State(object): def __init__ (self,country,capital): self.mas = (country, capital) def print_out(self) : print "The capital of %s is %s" % self.mas obj1 = State("Russia","Moskow") obj1.print_out()
Офлайн
1
terabaytя хочу из списка экземпляров вызывать методы этого экземпляра .
я не пойму что вы хотите сделать, но я бы сделал так
Офлайн
13
obj1 = State("Russia","Moskow") array = [obj1] for i in array: i.print_out()
Офлайн
13
array = [State(str(i), str(i/10)) for i in range(10)] for i in array: i.print_out() === OUTPUT === The capital of 0 is 0.0 The capital of 1 is 0.1 The capital of 2 is 0.2 The capital of 3 is 0.3 The capital of 4 is 0.4 The capital of 5 is 0.5 The capital of 6 is 0.6 The capital of 7 is 0.7 The capital of 8 is 0.8 The capital of 9 is 0.9 [Finished in 0.2s]
Офлайн
34
class State(object): class_instances = [] def __init__(self, country, capital): self.country = country self.capital = capital self.class_instances.append(self) @classmethod def print_out(cls): for state in cls.class_instances: print u'The capital of {} is {}'.format(state.capital, state.country) State('Russia', 'Moscow') State('Ukraine', 'Kiev') State('Belarus', 'Minks') State.print_out()
Отредактировано GreyZmeem (Янв. 12, 2015 03:13:27)
Офлайн
1
GreyZmeemСпасибо большое
Офлайн
34
State.class_instances.append(…)
Вы можете описать для чего вам сохранять все создаваемые объекты (да еще и в классах потомках)? Мне кажется что вы сильно усложняете себе задачу, когда действительно можно, как написал Alex_HH, все сохранять в обычный list.
Офлайн