Reputation: 87
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
Upvotes: 0
Views: 117
Reputation: 452
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.
Upvotes: 1
Reputation: 2665
Python and other OOP languages allow classes to inherit from baseclasses and even overide baseclass methods. Imagine the following! You have a base class for all characters in a game. The base class handles things like position, character name, an inventory, clothing, and is responsible for updating and rendering etc... You have an enemy sub-class that handles movement based on some algorithim, and a player sub-class that handles movement based on user input. Maybe the enemy doesn't need an inventory but the player does. Does that make sense?
Upvotes: 1
Reputation: 2585
new_shark.pi = 3.14
means add a new attribute to the class object(if not exists).
after the
new_shark.pi = 3.14
the class object will have:
self.name
self.age
self.pi
three attributes
Upvotes: 1