【问题标题】:Python- initialisation of built in variables/attributesPython-内置变量/属性的初始化
【发布时间】:2011-12-03 00:49:57
【问题描述】:

内置属性何时以及如何初始化? __doc__, __name__ (我想我知道这个:)), __class__, __setattr__ 等等。

在我关于文档字符串的另一个问题中,其中一个答案提到文档字符串只是简单的字符串,我尝试使用'"""",它们都有效。但是,当我使用分配字符串值的变量并将该变量代替文档字符串时,它不起作用。这就是为什么我开始想知道__doc__ 属性什么时候被初始化?

编辑: 这是我在解释器上尝试过的(是的,这很疯狂,我很奇怪: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!")

【问题讨论】:

  • “但是当我使用一个变量来分配字符串值并将该变量代替文档字符串时,它不起作用。”向我们展示。
  • @Sean,我刚刚点击了编辑链接,在此之前需要编辑文本,但页面加载完成了编辑 :) 好时机!

标签: python initialization init built-in docstring


【解决方案1】:

每个人都不一样。 (毕竟每个人的special!)有些是类属性,有些是实例属性,有些是继承的。

__doc__ 在创建类时被初始化(你也可以在dict 参数中将它传递给type 构造函数)。特殊语法仅适用于字符串文字,但如果您需要一个变量 docstring,您可以显式设置它:

class SomeClass(object):
    __doc__ = "This is class #{0}.".format(1)

__name__ 也是在创建类时设置的。

__class__ 在创建实例时设置(即在__new__ 中)。

__setattr__ 和好友继承自object

【讨论】:

  • 谢谢 :) 我正在学习一些我在书本上没有学到的东西(或者是 错过了它?)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-15
  • 2017-09-29
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 1970-01-01
  • 2012-12-15
相关资源
最近更新 更多