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"
Yes, you are correct. Each instance of an object type can have its own set of member data by assigning them to self.*
names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With