Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this work in Python? Creating a instance, setting a non existent attribute in that class, then printing that attribute through the instance

Tags:

python

oop

I was watching a Youtube tutorial about python classes.

This is the code he wrote.

class Tweet :
  pass

a = Tweet()

a.message = '140 chars'

print (a.message)

# This works

print(Tweet.message)

# This doesn't

I understand why printing tweet.message doesn't work (or at least I think I do if its as straightforward and simple as it seems) but why does printing a.message does? I'm assuming this is something to do with how python works but what is it?

Actually now that I'm thinking about it, maybe I have it wrong. I thought Tweet.Message doesnt print because tweet does have a message you can set. But does python automatically create the ability to do a.message ? So the reason tweet.message doesnt print it because that is only a blueprint, you can only retrieve data from instances, not the actual class itself?

like image 493
user7959439 Avatar asked Dec 09 '25 08:12

user7959439


1 Answers

Python allows dynamically adding new attributes to an object, even if it's not "declared" in the class signature, or assigned during object initialization in the __init__ method.

When you execute the assignment a.message = "...", the message attribute is added only to the a object, but not to the Tweet class, nor to any other objects with the same type. If you have another object b of Tweet type and you try to access its message attribute directly, you would get an AttributeError.

Here's a comprehensive example:

class Tweet:
  def __init__(self):
    self.user = "default_user"

a = Tweet()
print(a.user)     # "default_user"
a.message = "140 chars"
print(a.message)  # "140 chars"

b = Tweet()
print(b.user)     # "default_user"
print(b.message)  # AttributeError: 'Tweet' object has no attribute 'message'

print(Tweet.user)     # AttributeError: type object 'Tweet' has no attribute 'user'
print(Tweet.message)  # AttributeError: type object 'Tweet' has no attribute 'message'
like image 140
Zecong Hu Avatar answered Dec 10 '25 22:12

Zecong Hu