Member Variables vs Instance Variables


#1

I understand now what global variables and member variables are. Could someone please help me with instance variables?
I have tried Googling them but I am getting even more confused. I would be grateful if you could provide me with an example of the same.


#2

a little googling and i found this:

class TestClass(object):
    c = 299792458  #this is a class variable
 
    def __init__(self):
        self.e = 2.71 #instance variable
 
    def phiFunc(self):
        self.phi = 1.618 #will become an instance variable after phiFunc is called
        x=224 #this is a method variable and can't be accessed outside this method

which explains it nicely:

variable inside a class are class variable.
variable inside a method are method variable
variable added to self are instance variable


#3

Thanks a lot for the help! However my confusion arose because of the explanation provided in the exercises.

"When dealing with classes, you can have variables that are available everywhere (global variables), variables that are only available to members of a certain class (member variables), and variables that are only available to particular instances of a class (instance variables)." Thus a distinction has been made between member and instance variables

However according to what you have said here, the problem in exercise 20 refers to class variables and instance variables as member variables
a)Inside your Car class, replace the pass statement with a new member variable named condition and give it an initial value of the string "new".
b)Define the init() function of the Car class to take four inputs: self, model, color, and mpg. Assign the last three inputs to member variables of the same name by using the self keyword.

Which looks somewhat like this:-

class Car(object):
    condition="new"
    def __init__(self,model,color,mpg):
        self.model=model
        self.color=color
        self.mpg=mpg

my_car=Car("DeLorean","silver",88)

So after reading this my question is are class variables and instance variables = member variables, if yes then why has a distinction been made. If no, then what exactly is a member variable?


#4

okay, forget member variable. Its a term rarely used in Python. Its more a term for c/c++

condition is a class variable.

now, here:

my_car=Car("DeLorean","silver",88)

you initialize a class instance, and store this in a variable my_car.

now, self.model, self.color and self.mp are instance variable, because they belong to your my_car instance.


#5

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