3

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?

xarvis
  • 17
  • 6
Luke
  • 145
  • 5
  • Every list properties and methods are inheriting from List class – Eziz Hudayberdiyev Aug 14 '21 at 06:15
  • @EzizHudayberdiyev this makes sense, thank you! So every data type is a class. I'm assuming there is an integer class, string class, etc? Then an actual string, like my_string, is an instance (or object?) of this overarching class? – Luke Aug 14 '21 at 06:17
  • Related (Duplicate?): [How is Python's List Implemented?](https://stackoverflow.com/questions/3917574/how-is-pythons-list-implemented), ignore the accepted answer and look at the top voted one for the actual implementation – Sayse Aug 14 '21 at 06:23
  • @Luke yes, in Python, "type" and "class" are synonymous. exactly. If you want to dig a little deeper, classes themselves are *just instances of `type`*. – juanpa.arrivillaga Aug 14 '21 at 06:25
  • @Luke yes they are built-in data-types thats why you dont need to use `new` keyword – Eziz Hudayberdiyev Aug 14 '21 at 06:25
  • @EzizHudayberdiyev there is no `new` keyword in python – juanpa.arrivillaga Aug 14 '21 at 06:26
  • 1
    @juanpa.arrivillaga my bad im js dev, but you got what i mean ) – Eziz Hudayberdiyev Aug 14 '21 at 06:26
  • Thank you so much, that actually clarifies so much confusion. I guess the takeaway is that there is nothing special about int, or string, or list, etc, in Python, other than that they are built in presumably because they are the most commonly used types. – Luke Aug 14 '21 at 06:27
  • @Luke yes, Python is "purely object oriented". *Everything* is an object. There is no special cases like in, say, Java. Every object has a concrete type, i.e. a class – juanpa.arrivillaga Aug 14 '21 at 06:28
  • @Luke if you really want house data-type in python you need to contribute to python source code ) – Eziz Hudayberdiyev Aug 14 '21 at 06:29
  • I guess my other more pedagogical question is whether it is bad for someone with so little programming background to jump into something like Python, which is very high level. It seems I will miss a lot of this more deep conceptual understanding you all seem to have that I guess comes from a more low level or non-OOP language? – Luke Aug 14 '21 at 06:29
  • 1
    Bookmark this page: https://docs.python.org/3/reference/datamodel.html - it will be *very* useful and frequently referenced as you use Python. For this specific question, search for "Callable types" and particularly its subsection "instance methods". – o11c Aug 14 '21 at 06:31
  • @Luke conceptual understanding comes with time and experimence no matter whether language is high-level or not – Eziz Hudayberdiyev Aug 14 '21 at 06:33
  • @Luke - low level understanding is always a plus especially when debugging, ive worked with many a dev that got along fine without this. You’ll find many universities include some computer architecture class in the first year – Sayse Aug 14 '21 at 06:33

6 Answers6

2

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.

Aswin Murali
  • 61
  • 1
  • 3
  • 6
0

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.

  • typo at the end: I mean that you can make a custom class with it's own methods – Eisverygoodletter Aug 14 '21 at 06:17
  • So am I right in understanding that behind the scenes, there is some class defined called String or List or Integer that lets us manipulate these things. And we can manually define something else, like House? Then if you asked "what data type is this variable" the correct answer would be "House"? – Luke Aug 14 '21 at 06:20
  • Yes. Python can allow you to set a variable to any type, but other languages will not, like in C++ you need to tell the program that it is a string. You are correct – Eisverygoodletter Aug 14 '21 at 06:22
0

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.

xarvis
  • 17
  • 6
0

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

Sirius Koan
  • 51
  • 2
  • 4
0

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

Ram
  • 4,724
  • 2
  • 14
  • 22
0

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")
Radek Rojík
  • 104
  • 5