Reputation: 27
I'm trying to learn OOP and I can't find out how to initialize a list containing atributes initialized in another class.
class Player:
def __init__(self,name,skill_index):
self.name=name
self.skill_index=skill_index
class Team:
def __init__(self, playerlist):
self.playerlist='''Here I need to init a list of instances from Player class'''
return(playerlist)
So if I call it by print(Team([Player("Player1", [2, 3]), Player("Player2", [3, 1]]))
what should I write after self.playerlist=
to get the list? Very sorry for poor explanation, I'm a beginner.
Upvotes: 0
Views: 367
Reputation: 1125
Completing what you have already coded:
...
class Team:
def __init__(self, playerlist):
self.playerlist=playerlist
team = Team([Player("Player1", [2, 3])])
player = team.playerlist[0]
print(player.skill_index)
>> [2, 3]
To access members of a list, the position is used, starting from 0: some_list[position]
.
Just remember: __init__
shall not return ever and everything is an object
in Python, also lists; you can access properties of an element in a list by using the .
notation or getattr
built-in method.
UPDATE: to know the length of an iterable object use len()
Upvotes: 1