0

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

Panos
  • 77
  • 1
  • 7
  • _What is the point of creating a new attribute that doesn't follow the design of the class_ Python assumes that you know what you're doing, and it lets you do it. – John Gordon Sep 07 '19 at 03:24
  • OOP is primarily just a way to abstract problems to make them easier to understand. Python allows you to add an attribute as such to make it easier to keep the object model in place not only in theory but practice. – ShayneLoyd Sep 07 '19 at 03:43
  • Possible duplicate of [python class's attribute not in \_\_init\_\_](https://stackoverflow.com/questions/38710765/python-classs-attribute-not-in-init) – ComplicatedPhenomenon Sep 07 '19 at 03:52

3 Answers3

1
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

one
  • 2,205
  • 1
  • 15
  • 37
1

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?

TheLazyScripter
  • 2,541
  • 1
  • 10
  • 19
1

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.

Jason R
  • 416
  • 6
  • 13