定义一个带参数但不带参数的python函数

问题描述 投票:0回答:1

我正在尝试包装内置函数dir()以对其结果进行排序。如果我定义一个参数并将其传递给它,则可以正常工作。但是,如果我尝试让它显示根名称空间,它将无法工作,因为它要么需要一个参数,要么获取一个空对象,而该对象将为其返回属性。

我尝试用def dirs(*function): argv重新定义它,但是它返回一个列表,也不是当前作用域。

有没有办法用相同的功能包装此内置组件?我不了解C,所以内置源代码对我没有多大帮助,搜索显示了目录中文件的很多结果,但我似乎找不到如何破解它的方法。

def dirs(function):
    print '{}'.format(type(function))
    try:
        for i in sorted(dir(function)):
            print '{}'.format(i)
    except:
        for i in sorted(dir()):
            print '{}'.format(i)

我已经尝试过我能想到的所有数据类型,但是我无法在下面复制参考行为的行为。

print '# first for reference, a sorted dir()'
for i in sorted(dir()):
    print '{}'.format(i)
print '# next up: double quoted string'
dirs("")
print '# next up: None'
dirs(None)
print '# next up: empty dictionary'
dirs({})
print '# next up: empty set'
dirs(())
print '# next up: empty list'
dirs([])

这里是输出示例,为简洁起见,将其截断。

# Result:
# first for reference, a sorted dir()
FnOpenPluginInstaller
__allcompletions
[...]
tools_dir
windowContext
# next up: double quoted string
<type 'str'>
__add__
__class__
[...]
upper
zfill
# next up: None
<type 'NoneType'>
__class__
__delattr__
[...]
__str__
__subclasshook__
# next up: empty dictionary
<type 'dict'>
__class__
__cmp__
[...]
viewkeys
viewvalues
# next up: empty set
<type 'tuple'>
__add__
__class__
[...]
count
index
# next up: empty list
<type 'list'>
__add__
__class__
[...]
reverse
sort

python built-in
1个回答
1
投票

如何这样:

def dirs(function=None):
    if function is None:
        dirs_notsorted = dir()
    else:
        dirs_notsorted = dir(function)
    for i in sorted(dirs_notsorted):
            print('{}'.format(i))

 print(dirs())
 print(dirs([]))
© www.soinside.com 2019 - 2024. All rights reserved.