2016-06-10 16 views
1

我正在使用來自新sortedcontainers模塊的SortedListWithKey類(link)。有沒有辦法改變列表特徵來指定我想要一個SortedListWithKey(Instance(SomeClass), key=some_key)SortedListWithKey的性狀

更具體地講,如何才能做到這樣的:

from traits.api import HasTraits, Instance, SortedListWithKey # i know it cannot really be imported 

class MyClass(HasTraits): 
    sorted_list = SortedListWithKey(Instance(ElementClass)) 
+0

你的意思是一個'SortedListWithKey(實例(SomeClass的),關鍵= some_key)'? – mgilson

+0

抱歉不清楚。我想要的是一種使用'SortedListWithKey(Instance(SomeClass))'而不是'List(Instance(SomeClass))'的方法。 'key'部分是'SortedListWithKey'的細節,它是一個函數,用於定義列表元素是如何進行紅外線的。 – MindV0rtex

+0

它可能取決於你的情況'SomeClass'是什麼類。它當然需要是一個迭代器,然後你提供給'key'參數的東西需要是一個可調用的函數,作爲迭代器元素的比較點,它本身可以是一個Trait,就像簡單的例子如下: –

回答

1

你的問題再次尋找後,我想你在找什麼爲是訪問SortedListWithKey對象,就好像它是一個的方式列表並使用TraitsTraitsUI機器來驗證/查看/修改它。 Property特性在這裏可以幫助您查看SortedListWithKey作爲list。我已經修改我的代碼下面的例子有另一個特點是Property(List(Str)),並用一個簡單的TraitsUI查看:

from sortedcontainers import SortedListWithKey 

from traits.api import Callable, HasTraits, List, Property, Str 
from traitsui.api import Item, View 


class MyClass(HasTraits): 
    sorted_list_object = SortedListWithKey(key='key_func') 

    sorted_list = Property(List(Str), depends_on='sorted_list_object') 

    key_func = Callable 

    def _get_sorted_list(self): 
     return list(self.sorted_list_object) 

    def default_key_func(self): 
     def first_two_characters(element): 
      return element[:2] 
     return first_two_characters 

    def default_traits_view(self): 
     view = View(
      Item('sorted_list', style='readonly') 
     ) 
     return view 


if __name__ == '__main__': 
    example = MyClass() 
    example.sorted_list_object = SortedListWithKey(
     ['first', 'second', 'third', 'fourth', 'fifth'] 
    ) 
    example.configure_traits()