Ask Question
14 September, 03:27

How does object-oriented programming work in Python?

+2
Answers (1)
  1. 14 September, 04:16
    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?
Get an answer to your question ✅ “How does object-oriented programming work in Python? ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers