list - [Python ]Using variables defined inside a class (before __init__) in its own methods (__init__, etc.) -
i'm trying make basket can put fruit. basket class, called basket, has internal list called contents. every time basket fruit instance created, it's self.name property appended contents. anyhow, doesn't work.
contents = [] class basket: ## want define list "contents", ## doesn't work. def __init__(self,name): self.name = name global contents if name not in contents: contents.append(name)
for reason, works if define list contents outside class altogether, affect order , debugging in bigger projects.
is there way make code work, lets me define list inside class? if make class-specific "global"variable, valid methods/variables inside class.
note: class supposed 1 basket! each fruit called basket itself, fruit. want them inside 1 basket.
this whole answer lengthy explanation why shouldn't doing you're trying do...
"note: class supposed 1 basket! each fruit called basket itself, fruit. want them inside 1 basket."
before making attempt solve riddle, actual question must put in perspective.
- you're dealing 2 nouns -
fruit
,basket
- they have associative relationship: independent, related.
"each fruit called basket"
capital mistake! chessboard , chess pieces. 1 cannot other.
"i want them inside 1 basket."
if "all" meant "all fruits", done.
to put things in perspective, first modify class names follows:
class fruit(object): def __init__(self, name): self.name = name
now there must object called basket
keep track of fruits. doesn't have class. can make dictionary, set, list or other container.
basket = set()
is simple set can hold fruits. each time when make fruit, can automatically add name basket:
basket = set() class fruit(object): def __init__(self, name): self.name = name # needed! basket.add(name)
to test code:
# making fruits name in ["apple", "orange", "banana"]: fruit(name) # checking basket print(basket)
the output follows:
{'banana', 'apple', 'orange'}
now, if want add more functionality basket
object, can make in class follows:
class basket(object): def __init__(self, fruits=none): self.fruits = fruits or set() def put(self, fruit): """add fruit basket.""" self.fruits.add(fruit) def show(self): """display fruits in basket.""" fruit in self.fruits: print(fruit.name) class fruit(object): def __init__(self, name, basket=none): self.name = name # adding basket if needed. if basket not none: basket.put(self) # making 2 baskets gift = basket() picnic = basket() # making fruits , adding them both baskets apple = fruit("apple", basket=gift) orange = fruit("orange", basket=picnic) banana = fruit("banana", basket=gift) print("in gift basket have:") gift.show() print("in picnic basket have:") picnic.show()
and output:
in gift basket have: banana apple in picnic basket have: orange
Comments
Post a Comment