Reputation: 8287
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!")
Upvotes: 2
Views: 552
Reputation: 66950
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 the dict
argument to the type
constructor). The special syntax only works for string literals, but if you need a variable docstring you can set it explicitly:
class SomeClass(object):
__doc__ = "This is class #{0}.".format(1)
__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 from object
.
Upvotes: 2