Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 330
Luke Avatar asked Sep 07 '25 04:09

Luke


1 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.

like image 94
Aswin Murali Avatar answered Sep 09 '25 20:09

Aswin Murali