Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the same Python objects vary in size since there is no formal initialization?

I'm trying to learn some basic Python object design. One thing I noticed is that python doesn't require you to list out all data members before you are able to use them within the class. Instead, I've noticed that you are able to introduce new data members throughout different method calls on a class.

Referring to the code below, notice how I use the constructor to declare a self.hello_world member. Because the constructor is called for every instance of that class, I am certain that every object will contain a hello_world member.

However, notice how I create a self.dog data member ONLY if I call the printTest method. This data member would not exist if I don't call this method.

So my question, unlike the programming language C++ in which all objects must have a certain object size, can python objects instantiated from the same class vary in size due to what I pointed out?

Thank you!

# Class test

class TestClass:


    def __init__(self):
        self.hello_world = 49

    def printTest(self):
        print("Trying to create new data member /n")
        self.dog = "Biscuit"
like image 840
Izzo Avatar asked Sep 16 '25 14:09

Izzo


1 Answers

Yes, you are correct. Each instance of an object type can have its own set of member data by assigning them to self.* names.

like image 76
Mark Harrison Avatar answered Sep 19 '25 06:09

Mark Harrison