Gennaro
Gennaro

Reputation: 113

Appending Item to list in a Class

class Drinks:
  def __init__(self):
    self.drink = ['Coke']
    self.count = 0
    self.alcohol_level = [1]
def main():
    Drinks().alcohol_level.append(89)

I want to append to the level list, not quite sure how to go about it.

What I've tried is:

    Drinks().alcohol_level.append(89)

But that's obviously not correct. Any help is appreciated. Thanks!

Upvotes: 0

Views: 58

Answers (1)

Skam
Skam

Reputation: 7798

First off, your class definition is fine. Good job!

Bad news, I think, you're misunderstanding how instances of classes work.

Drinks() is a constructor that returns a type Drink.

If you wanted to create an instance of type Drink you would use do d = Drinks(). d.alcohol_level is now [1].

To answer you question, suppose you call d.alcohol_level.append(2).

d.alcohol_level is now [1, 2]

If you created b = Drinks(), b.alcohol_level is [1] since alcohol_level is an instance variable and each instantiation, or call to your Drink constructor, creates a Drink object with its own properties defined in your class.

def main():
  d = Drinks()
  d.alcohol_level.append(2)
  # print(d.level) -> [1, 2]

if __name__ == '__main__':
  main()

Your original idea was close but you lose reference to that modified Ditto instance after the line Ditto().level.append(2).

You did the Python equivalent of doing your homework then burning it immediately after.

Upvotes: 4

Related Questions