python 术语说明
Clarification on python terminology
我写过一段代码:
def Greeting():
return "Hello there!"
Greeting.help = "This function will say hello"
print(Greeting())
print(Greeting.help)
我不确定 Greeting.help 会叫什么...我试过搜索,但我觉得我使用了错误的搜索词。
您已经设置了对象(在本例中为函数对象)的单个属性。
如果你想记录它,那么更传统的方法是设置文档字符串:
def Greeting():
""" This function will say hello """
return "Hello there!"
然后可以通过help(Greeting)
查看:
>>> def Greeting():
... """ This function will say hello """
... return "Hello there!"
...
>>> Greeting.__doc__
' This function will say hello '
>>> help(Greeting)
它打印:
Help on function Greeting in module __main__:
Greeting()
This function will say hello
(END)
您已为对象 Greeting
设置了 属性 。这就是为什么相应的函数被称为 getattr
和 setattr
的原因。
>>> getattr(Greeting, 'help')
'This function will say hello'
>>> setattr(Greeting, 'foo', 'bar')
这些属性存储在字典 Greeting.__dict__
中,也可以通过 vars(Greeting)
访问。
>>> Greeting.__dict__
{'foo': 'bar', 'help': 'This function will say hello'}
>>> vars(Greeting)
{'foo': 'bar', 'help': 'This function will say hello'}
请注意,设置 help/docstring 的惯用方法如下:
>>> def foo():
... 'help text'
... pass
...
>>> foo.__doc__
'help text'
我写过一段代码:
def Greeting():
return "Hello there!"
Greeting.help = "This function will say hello"
print(Greeting())
print(Greeting.help)
我不确定 Greeting.help 会叫什么...我试过搜索,但我觉得我使用了错误的搜索词。
您已经设置了对象(在本例中为函数对象)的单个属性。
如果你想记录它,那么更传统的方法是设置文档字符串:
def Greeting():
""" This function will say hello """
return "Hello there!"
然后可以通过help(Greeting)
查看:
>>> def Greeting():
... """ This function will say hello """
... return "Hello there!"
...
>>> Greeting.__doc__
' This function will say hello '
>>> help(Greeting)
它打印:
Help on function Greeting in module __main__:
Greeting()
This function will say hello
(END)
您已为对象 Greeting
设置了 属性 。这就是为什么相应的函数被称为 getattr
和 setattr
的原因。
>>> getattr(Greeting, 'help')
'This function will say hello'
>>> setattr(Greeting, 'foo', 'bar')
这些属性存储在字典 Greeting.__dict__
中,也可以通过 vars(Greeting)
访问。
>>> Greeting.__dict__
{'foo': 'bar', 'help': 'This function will say hello'}
>>> vars(Greeting)
{'foo': 'bar', 'help': 'This function will say hello'}
请注意,设置 help/docstring 的惯用方法如下:
>>> def foo():
... 'help text'
... pass
...
>>> foo.__doc__
'help text'