1
class Sample:
    pass


sample = Sample()
sample.a = "magic"

print(sample.a)

In the code above, i create an empty class Sample and was able to add set an attribute outside the class definition. Trying to do the same with an instance of str but I encounter AttributeError: 'str' object has no attribute 'a'. Why can't I do the same with an instance of str. Does it have anything to do with str being a primitive type?

sample_string = ""
sample_string.a = "magic"

print(sample_string.a)
Ser.T
  • 51
  • 4

1 Answers1

1

Most builtin classes in python won't let you assign arbitrary attributes. You can base subclasses of your own on a lot of them (such as list and dict) and then do so.

str is a bit special because of the immutable nature - essentially python can avoid having multiple buffers for the same string by always using the same one. You can however still subclass it by overriding new instead of init: How to subclass str in Python

Abel
  • 437
  • 4
  • 7