Ask Question
9 May, 19:57

How does object-oriented programming work in Python?

+1
Answers (1)
  1. 9 May, 22:42
    0
    So basically you have a class, and within that class you have methods and instance variables; very much like how object oriented programming works in other languages. However, the main difference is that the class constructor in Python is defined right within the class object and is denoted by the method name, "__init__" and requires a parameter of "self".

    Ex:

    class Py:

    def __init__ (self):

    constructor code ...

    The __init__ method is what is called first when an object of the class is instantiated. The way you instantiate an object is by the following:

    object_name = Py ()

    If you wanted to make your class more useful, you could add more parameters to your __init__ constructor, so when an object is created you can pass arguments to that object:

    class Py:

    def __init__ (self, name, age):

    self. name = name

    self. age = age

    print "Your name is %s and you are %d years old" % (name, age)

    def main ():

    Bob = Py ("Bob", 23)

    if __name__ = = "__main__":

    main ()

    This code would give you: Your name is Bob and you are 23 years old
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “How does object-oriented programming work in Python? ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers