Reputation:
I have a class Laby that provide a list of tuple (self.paths) and I have a class item that create items.
I am building a method where the items are place randomly using random.sample, I want to use the list from my laby class instead of the attribute my_list from my set_position method.
This is my laby :
class Laby:
def __init__(self):
self.paths = [] # it received some data from another function.. inside a list is created of tuples
This is my Item Class
class Item:
# add item to path / randomize pos /
def __init__(self, title):
self.title = title
self.position = (0,0)
def set_position(self):
my_liste = [(0, 1),(2,4),(4,2),] #instead of my list I want to use the path attribute from Laby
self.position = random.sample(my_liste, 1)
item1 = Item('Object')
item1.set_position()
print('Random pos: ', item1.position , 'Name: ',item1.title)
Upvotes: 0
Views: 42
Reputation: 4274
I don't think so, This is what you want or not?
If I'm wrong, help me to find it out in comments.
You can pass a Loby
instance to the set_position
method. (If this method can accept parameters)
import random
class Laby:
def __init__(self):
self.paths = []
def set_paths(self, paths):
self.paths = paths
def get_paths(self):
return self.paths
class Item:
def __init__(self, title):
self.title = title
self.position = (0, 0)
def set_position(self, laby):
my_liste = laby.get_paths()
self.position = random.sample(my_liste, 1)
paths = [(0, 1), (2, 4), (4, 2), ]
# initialize laby
laby1 = Laby()
laby1.set_paths(paths)
item1 = Item('Object')
item1.set_position(laby1)
print('Random pos: ', item1.position, 'Name: ', item1.title)
Output:
Random pos: [(2, 4)] Name: Object
Upvotes: 1
Reputation: 125
As per my understanding of your problem i am presenting below code:
import random
class Laby(object):
def __init__(self):
self.paths = [(0, 1),(2,4),(4,2)]
class Item(Laby):
# add item to path / randomize pos /
def __init__(self, title):
self.title = title
self.position = (0,0)
def set_position(self):
super(Item, self).__init__()
self.position = random.sample(self.paths, 1)
item1 = Item('Object')
item1.set_position()
print('Random pos: ', item1.position , 'Name: ',item1.title)
Upvotes: 0