Search code examples
pythonclassoopinstance-variablesclass-variables

what's the meaning of creating new variables at a class instance?


I am new to OOP programming in python and I was wondering why python let us create new attributes at an object instance. What is the point of creating a new attribute that doesn't follow the design of the class ?

class Shark:
    def __init__(self, name, age):
        self.name = name
        self.age = age

new_shark = Shark("Sammy", 5)
print(new_shark.age)
new_shark.pi = 3.14
print(new_shark.pi)

I expected that python will produce an error but it prints 3.14

*Each answer covered a different spectrum. Thank you very much


Solution

  • Here is a link to a similar question with lots of helpful answers: Why is adding attributes to an already instantiated object allowed?

    Now for my answer. Python is a dynamic language meaning that things can be changed at run time for execution. But what is important to realize is that the answer to your question is more a matter of style and opinion.

    Instantiating your class with all the needed variables inside of it gives you the benefit of encapsulation and the safety of knowing that every time the class is instantiated that you will have access to that variable. On the other hand adding a variable after instantiation may give you different benefits in specific use cases.