Ask Question
18 June, 16:50

How does object-oriented programming work in Python?

+4
Answers (1)
  1. 18 June, 17:00
    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 & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers