【问题标题】:Confusion to figure out between attribute or method in Python混淆Python中的属性或方法
【发布时间】:2021-05-04 12:46:50
【问题描述】:

根据以下线程

How to differentiate between classes, functions, and methods

snake_case 用于确定其是否为特定类型的函数和方法。

我正在查看 string 模块,我查看了 print(dir(string)) 并得到了所有这些

[Formatter,Template,_ChainMap,_TemplateMetaclass,__all__,__builtins__,__cached__,__doc__,__file__,__package__,__package__,@989 @,__spec__,_re,_sentinel_dict,_string,ascii_letters,ascii_lowercase,ascii_uppercase,capwords,digits,octdigits,octdigits,octdigits,@987654347 punctuation, whitespace]

我只是想使用string.ascii_lowercase 获取一系列字母 但是根据上面提到的链接,ascii_lowercase 不是method 吗?并且method 需要被称为ascii_lowercase()。但它不起作用,他们是区分什么是什么的清晰方法吗?

我在这里很困惑,请有人帮助我。

编辑 1: 为了更清楚地说明我的问题,instance 通常确实有 attributesmethods 甚至 method 被认为是 attributeinstance ,所以这就是我感到困惑的地方。

【问题讨论】:

  • 如文档所述,dir 返回在参数符号表(目录)中定义的符号列表。这包括属性和方法。一个简单的测试会告诉您删除括号会返回指定的字母表。
  • @prune 你刚刚提到了我已经说过的关于 'dir()' 的内容,它提供了属性和方法,但实际上并没有回答我的问题。
  • 你的问题是如何得到字母表。我确实回答了。您的问题表明您对如何获得它感到困惑。

标签: python methods module attributes


【解决方案1】:

您可以通过检查符号的类型轻松区分。例如:

>>> type(str.isupper)
<class 'method_descriptor'>
>>> type(string.ascii_lowercase)
<class 'str'>

也许不那么直接,你阅读包文档。

【讨论】:

    【解决方案2】:

    string.ascii_lowercase 保存字符串值:

    >>> import string
    
    >>> string.ascii_lowercase
    'abcdefghijklmnopqrstuvwxyz'
    

    要知道属性的类型,可以在getattr() 上使用type()。这是显示dir(string)返回的所有值类型的示例:

    for x in dir(string):
        print("'{}' - {}".format(x, type(getattr(string, x))))
    
    # which print the output as:
    #   'Formatter' - <type 'type'>
    #   'Template' - <class 'string._TemplateMetaclass'>
    #   '_TemplateMetaclass' - <type 'type'>
    #   '__builtins__' - <type 'dict'>
    #   '__doc__' - <type 'str'>
    #   '__file__' - <type 'str'>
    # .... so on ....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多