簡體   English   中英

定義一個 python function 它需要 arguments 但也可以不帶參數工作

[英]Define a python function which takes arguments but also works with no argument

我正在嘗試包裝內置的 function dir()以對其結果進行排序。 如果我定義並向它傳遞一個參數,它就可以正常工作。 但是,如果我試圖讓它顯示根命名空間,它將無法工作,因為它要么需要一個參數,要么得到一個空的 object,它返回屬性。

我嘗試用def dirs(*function): argv 重新定義它,但它返回一個列表,而不是當前的 scope。

有沒有辦法用相同的功能包裝這個內置的? 我不知道 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([])

這是 output 的示例,為簡潔起見被截斷了。

# 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

這樣的事情怎么樣:

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([]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM