Are all variables in Python some object of a class? Or are they classes themselves?

Viewed 157

I am a complete beginner to programming so this may be a ridiculous or simple question.

I am trying to understand exactly what a "method" is. The standard answer is that it is a function associated to a class. The syntax seems to be something like user Gustav Rubio's answer which is,

class Door:
  def open(self):
    print 'hello stranger'

def knock_door:
  a_door = Door()
  Door.open(a_door)

knock_door()

So the the method is open() since it is associated with the class Door.

But if we define a list, we can also use the "append method", which looks something like

my_list = ["milk", "eggs"]
my_list.append("bread")

So does this mean that every list is a class? Since we are writing it in the form class_name.method_name? In general, is every variable a special case of a class? Or is there some other use of the term "method" here?

Again I apologise if this is too basic for this form. I was also wondering if there is a non-overflow version, much like mathstackexchange vs mathoverflow for more basic questions like this?

6 Answers

Python is an object-oriented language, where every variable is an object/reference to an object.

Look at the below code,

class Hi:
   pass

>>> h = Hi()
>>> type(h)
<class '__main__.Hi'>
>>>

This was expected. Now let's look at a list,

>>> mylist = []
>>> type(mylist)
<class 'list'>
>>>

We can see that mylist is indeed an object of the list class. It's an instance and not the class itself because the methods inside it will only affect mylist instance.

"The list data type has some more methods. Here are all of the methods of list objects". Taken from python's official "list" documentation. https://docs.python.org/3/tutorial/datastructures.html

From the above statement, we can clearly understand that mylist is an object of the list class and not the class itself.

Yes, append is a method of the array, yes, you can think of every variable as having a different type of "class". The exact definition of "class" may vary across different languages, but it often means a type of data, like a word, a letter, a number, a decimal number... etc. You can make your own class like "house" that has methods its own methods, then use that class as the type for a variable.

In this scenario my_list = ["milk", "eggs"] will return a object containing values "milk" and "eggs". And the returned list object implemented append method internaly.

If you try type(1), you will get <class 'int'>. Similarly, type([1,2,3]) is <class 'list'> and type("abc") is <class 'str'>, and if you type d = Door() and then type(d), you'll get <class '__main__.Door'>.

Every list is an instance of class list (also called object) and they are not classes by themselves.

All the methods of list class can be used by its objects in the same way a_door (which is an instance of class Door) in your code uses open()

The below example will make it clear to you.

isinstance(a, b) - Returns True if a is an instance of class b

a = ['apple', 'banana', 'cherry']
b = "Hello World"
c = 33

print(type(a))
print(isinstance(a,list))
print(type(b))
print(type(c))

class Door:
  def open(self):
    print('hello stranger')
    
    
def knock_door():
    a_door = Door()
    print(type(a_door))
    print(isinstance(a_door, Door))
    Door.open(a_door)

knock_door()
<class 'list'>
True
<class 'str'>
<class 'int'>
<class '__main__.Door'>
True

The term method and function are different.

Method is similar to a function except that it is associated with an object.

In your code,

  • open() is called a method since it is associated with objects of type Door.
  • knock_door() is a function.

Please read this to know the difference. - Method vs Function

I think it's better to understand this way:

class Door:
    def add(self, where):
        # We added room door and let's close (value = False)
        setattr(self, where, False)
        print(f"The door {where} was added")
    
    def switch(self, where):
        try:
            if self.__getattribute__(where):
                # The door is open = True
                print(f"I closed the {where} door")
                setattr(self, where, False)
            else:
                # The door is close = False
                print(f"I opened the {where} door")
                setattr(self, where, True)
        except AttributeError:
            print(f"I don't know {where}")


mydoor = Door()  # make object/instance from class
mydoor.add("kitchen")  # call method on instance
mydoor.switch("kitchen")  # call method on instance
mydoor.switch("kitchen")  # call method on instance
mydoor.switch("Bedroom")  # call method on instance
# You can make test open or close:
print(f"The door is open: {mydoor.kitchen}")
# You can added other door and make it open simply:
mydoor.showroom = True
print(f"The door is open: {mydoor.showroom}")
# And let's close it:
mydoor.showroom = False
# And again open with our method:
mydoor.switch("showroom")
Related