python - Inheriting from "str" class -
I'm exercising this little bit ... I want to reorder a string based on some weird dictionaries . For example, according to my dictionary, the letters come in order: "A", "B", "D", "C", "F", "E"
So I thought that I Should just & lt; The operator and the call sorted for the wire ()
goes here:
class MyString (str): new_dict = dict ((x, i) for i Enumerate in X (["A", "b", "d", "c", "f", "e"])) DEF __lt __ (self, others): return self. NY_act [self] & lt; Self [ND] [Other] DEF __int __ (self, X): str .__ init __ (self, x) and then
[59]: Sorted (Mysterrine (Ex)) for X in (ABCDF) [59]: ['A', 'B', 'D', 'C', 'F', 'E' ] [64]: [64]: "abdcfe" in [64]: MyString (included in "". (Sorted (Mycring (x) "abcdef" In x)) [64]: 'abdcfe' But why can not I just sort (Mysterrine ("abcdef")) ? < / P> in [70]: ['A', 'B', 'C', 'D', 'E', 'A Apparently returning to the Mythreen Iterator. In [72]: In the maste ("abcdef"): Print Type (i) ....: & lt; type 'str' & gt; type 'str' & gt; type 'str' & gt; type 'str' & gt; Type 'str' & gt; Type 'str' & gt; If I call upon joining the maststring:
In [63]: type (mystrain (""). Include (sorted ("abcdef" for the migrating (X)))) Out [63]: str Why is MyString str iterators?
You must override here:
class MyString (str) : Def __getitem __ (self, i): return type (self) (super (migrating, self) .__ getitem __ (i)) This gives a new example of the current type :
& gt; & Gt; & Gt; I ("abcdef") in mystring: ... print type (i) ... class' __man____. MyStress' & gt; & Lt; Class' __men __. MyStress' & gt; & Lt; Class' __men __. MyStress' & gt; & Lt; Class' __men __. MyStress' & gt; & Lt; Class' __men __. MyStress' & gt; & Lt; Class' __men __. MyStress' & gt; str does not apply its own running (it does not, but does apply the sequence protocol (both of these <__lan __ length method a a __ getitem __ method); it is that for loop ultimately uses). If Python 3 performs a __ iter __ method in and you need to override it Is: class MyString (str): def __iter __ (self): return (type (self) (i) for i super () .__ iter __ ()) Note that str is an irreversible type, which can be overridden by __init __ . For the order, you can actually enter all the __ gt __ , __GI __ , __eq __ , etc. Also use yourself to save most of the work from here: Import from function stroke total_ordeedeng @total_ordering class MyString (str): sortmap = {x: i for i, in x Enumerate ("abdcfe")} Def __lt __ (self, others): return self. Format [self] & lt; Self. Steppap [Other] SRF __getitem __ (relative to self, i) __eq__: return type (self) (super (migrating, self) .__ getitem __ (i)) last but sorting For at least, just type the key argument to () use here: & gt; & Gt; & Gt; For sortmap = {x: i, enumerate in x ("abdcfe")}> gt; & Gt; & Gt; Sorted ('abcdef', key = sortmap.get) ['a', 'b', 'd', 'c', 'f', 'e'] / Html>
Comments
Post a Comment