AlasdairRyan AlasdairRyan - 26 days ago 8
Python Question

Python iterate through a list of class objects and extract a value

Hello I am having some trouble with trying to iterate through a list of classes in order to print out a particular value that thet instance of that class holds.My program compiles but it does not print any thing out, I have also tried having "player.player in playerlist" in the for loop but I also got the same result.Any help would be greatly appreciated.

My main function

class main:

if __name__ == '__main__':

while True:

print("Please Select An Option Below:")
print("1 - Create Player:")
print("2 - List Players:")
print("3 - Create Team:")
print("4 - Sell Player:")
print("5 - Buy Player:")
x = raw_input("Please select a option: \n")

playerList = []

if(x == '1'):

import Player
p1 = Player.player()
pname = raw_input("Please Enter A Player Name \n")
page = raw_input("Please Enter A Player Age \n")
pwage = raw_input("Please Enter A Player Wage \n")
pteam = raw_input("Please Enter A Player Team \n")
p1.pname = pname
p1.page = page
p1.pwage = pwage
p1.pteam = pteam
playerList.append(p1)
continue

if(x == '2'):
for p1 in playerList:
print(p1.pname)
continue


My player class

class player(object):

@property
def pname(self):
return self.pname

@pname.setter
def pname (self, value):
pass

@property
def page(self):
return self.page

@page.setter
def page (self, value):
pass

@property
def pwage(self):
return self.pwage

@pwage.setter
def pwage(self, value):
pass

@property
def pteam(self):
return self.pteam

@pteam.setter
def pteam(self, value):
pass


----update-----

class main:

if __name__ == '__main__':

while True:

print("Please Select An Option Below:")
print("1 - Create Player:")
print("2 - List Players:")
print("3 - Create Team:")
print("4 - Sell Player:")
print("5 - Buy Player:")
x = raw_input("Please select a option: \n")

playerList = []

if(x == '1'):

import Player
nplayer = Player.player()
nplayer.set_name(raw_input("test\n"))
playerList.append(nplayer)
continue

if(x == '2'):
for player in playerList:
print(player.get_name)
continue

class player(object):

__name = ""

@property
def get_name(self):
return self.__name

def set_name(self, name):
self.__name = name

Answer

When you write p1.pname = pnamethe setter is called. However, you don't do anything in the setter. So when the getter is called later, it doesn't have anything to return.

For getters and setters to work in python, you need to do something like this:

class player(object):
    @property
    def pname(self):
        return self._pname

    @pname.setter
    def pname (self, value):
        self._pname = value