6. Referring to member variables - Member Variables Clarification


#1

Link to lesson: https://www.codecademy.com/courses/python-intermediate-en-egNXj/0/6?curriculum_id=4f89dab3d788890003000096

Member variables that are arguments of the init function have to be defined within the function as self.variable = variable. Is this still the same with member variables outside of the init function? If not, why?

For example, in my code, the member variable condition does not have to be defined as self.condition in the init function. Why is this?

class Car(object):
    condition = "new"
    def __init__(self, model, car, mpg):
        self.model = model
        self.car = car
        self.mpg = mpg
my_car = Car("DeLorean", "silver", 88)
print my_car.condition


#2

condition is called class variable and its completely owned by class.
The value of this variable is same for all instances of class(Tho we can change it)

on the other hand the variables defined inside the constructor ( __init__) are called instance variable and their values will be be different for different instances.

Check documentation of python here:
Link


#3

That should be color.


#4

As you've already learned from above, it is a class variable that is inherited by all instances. We still need to refer to it with self if being polled from within any methods of the class.

def display(self):
    print self.condition

#5

What I meant to ask is why instance variables need to be defined as self.variable = variable when class member variables don't. Like I mentioned, condition does not need to be defined as self.condition, but color needs to be defined as self.color within the init function. Why?


#6

Like class variables, self exists at the top of the class scope chain. The parameters passed into the __init__ method cannot attach themselves to the instance without self, which must also be passed into the mthod.

If we do not have in init method in a class then we have no real way to create unique instances. We can instantiate, but every instance will be same. It would become necessary to set each variable manually.

>>> class Bar(object):
	foo = '7'
	bar = '6'

	
>>> b = Bar()
>>> b.foo
'7'
>>> b.bar
'6'
>>> c = Bar(6, 7)
Traceback (most recent call last):
  File "<pyshell#221>", line 1, in <module>
    c = Bar(6, 7)
TypeError: object() takes no parameters
>>> c = Bar()
>>> c.foo
'7'
>>> c.foo = 6
>>> c.bar = 7
>>> c.foo, c.bar
(6, 7)
>>> b.foo, b.bar
('7', '6')
>>>

#7

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