When and how are the builtin attributes initialized?
__doc__, __name__ (I guess I know about this one 🙂 ), __class__, __setattr__ etc.
In my other question regarding docstrings, one of the answers mentioned that docstrings are just simple strings and I tried with ', " and """ and they all worked. But when I used a variable assigned the string value and put that variable in place of the docstring, it doesn’t work. That’s why I started wondering when does the __doc__ attribute get initialized?
EDIT:
This is what I have tried on interpreter (yes, this is crazy and I am wierd :D)
doc_str = "Says Hello world"
class HelloWorld():
def say():
doc_str
print("Hello world !")
h_w = HelloWorld()
h_w.say.__doc__
class AnotherHelloWorld():
def __init__(self, doc_str="Says HELLO WORLD"):
self.doc_str = doc_str
def say(self):
self.doc_str
print("HELLO WORLD !")
a_h_w = AnotherHelloWorld("Scream... HELLO WORLD!")
a_h_w.say.__doc__
class YetAnotherHelloWorld():
def __init__(self, doc_str="Still does't say HELLO WORLD :( "):
self.doc_str = doc_str
def say(self):
"%s"%self.doc_str
print("HELLO WORLD .. Again!")
It’s different for each one. (After all, each one’s special!) Some are the class attributes, some are instance attributes, some are inherited.
__doc__is initialized when the class is created (you can also pass it in thedictargument to thetypeconstructor). The special syntax only works for string literals, but if you need a variable docstring you can set it explicitly:__name__is also set when the class is created.__class__is set when an instance is created (i.e. in__new__).__setattr__and friends are inherited fromobject.