Do both mean the same thing? (Member variables)


#1


Am I correct to say that in the second case, I created a new member variable is_alive?

class Animal(object):
    """Makes cute animals."""
    is_alive = True   # member variable
    def __init__(self, name, age):
        self.name = name
        self.age = age

class Animal(object):
    """Makes cute animals."""
   
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.is_alive = True    # Is this a member variable?


#2

seems not to be the case, from python doc:

class Dog:

    tricks = []             # mistaken use of a class variable

    def __init__(self, name):
        self.name = name

    def add_trick(self, trick):
        self.tricks.append(trick)

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks                # unexpectedly shared by all dogs
['roll over', 'play dead']

Correct design of the class should use an instance variable instead:

class Dog:

    def __init__(self, name):
        self.name = name
        self.tricks = []    # creates a new empty list for each dog

    def add_trick(self, trick):
        self.tricks.append(trick)

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks
['roll over']
>>> e.tricks
['play dead']

we place tricks inside init, on which python doc says: use an instance variable

so anything inside of __init__() is seen as instance variable

what is called member variable here in the lessons, is called class variables in the doc


#3

Right nice explanation! Thanks!


#4

not really? I just stole from the docs xD

But good it clarifies something


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.