python之dir函数

python之dir函数,第1张

1、dir函数

dir()函数的参数是你传入的对象,它会返回对象的属性和方法。比如字符串,当你不记得某个方法的拼写就可以用该函数查询字符串的所有方法。

2、使用
  1. 查询字符串,一个双引号就是字符串类,所以以下代码就是查询字符串的所有属性。
    print(dir(""))

[’__add__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__getnewargs__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mod__’, ‘__mul__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__rmod__’, ‘__rmul__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘capitalize’, ‘casefold’, ‘center’, ‘count’, ‘encode’, ‘endswith’, ‘expandtabs’, ‘find’, ‘format’, ‘format_map’, ‘index’, ‘isalnum’, ‘isalpha’, ‘isdecimal’, ‘isdigit’, ‘isidentifier’, ‘islower’, ‘isnumeric’, ‘isprintable’, ‘isspace’, ‘istitle’, ‘isupper’, ‘join’, ‘ljust’, ‘lower’, ‘lstrip’, ‘maketrans’, ‘partition’, ‘replace’, ‘rfind’, ‘rindex’, ‘rjust’, ‘rpartition’, ‘rsplit’, ‘rstrip’, ‘split’, ‘splitlines’, ‘startswith’, ‘strip’, ‘swapcase’, ‘title’, ‘translate’, ‘upper’, ‘zfill’]

同理,
2. 查询元组
print(dir(()))
3. 查询列表
print(dir([]))
4. 查询字典
print(dir({}))

3、查询非内置类

除了上述内置类可以查询,所有对象都可以查询,所以如果我们自己写的类也是可以查询的,查询方法一样。

首先,定义一个类:

class DIR_Test:
    def __init__(self, a):
        self.a = a
        self.b = 2
        self.c = "hello dir"

    def train(self):
        pass

    def eval(self):
        pass

先来看看不实例化,直接查询:
print(dir(DIR_Test))

[’__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’, ‘eval’, ‘train’]

如果实例化后,再查询:
dir_test = DIR_Test(a=1)
print(dir(dir_test))

[’__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’, ‘a’, ‘b’, ‘c’, ‘eval’, ‘train’]

可以看出:

  • 没有实例化后查询,只能看到方法;实例化后再查询,可以看到方法和属性。因为只有实例化后才能把属性的值定下来,所以正确的使用方法是先实例化再使用。
  • 比如上面查询列表,传入的是"[]"实际上就已经实例化了一个对象。
  • dir查询到的属性是没有值的

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/715074.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存