覆盖内置类型方法

时间:2018-09-19 01:10:52

标签: python python-3.x

在“ fluent_python”的继承章节中,它演示了一个替代替代内置类型的示例

In [50]: class AnswerDict2(collections.UserDict):
    ...:     def __getitem__(self, key):
    ...:         return 42
    ...:    

它可以按照作者的意图正常工作

In [60]: ad = AnswerDict2(a="foo")

In [61]: ad["a"]
Out[61]: 42

In [62]: d = {}

In [63]: d.update(ad)

In [64]: d
Out[64]: {'a': 42}

但是,广告的原件仍未覆盖:

In [65]: ad
Out[65]: {'a': 'foo'}

怎么可能呢?

In [65]: ad
Out[65]: {'a': 42}

1 个答案:

答案 0 :(得分:1)

您可以改用Dim count = ListView1.Items.Count - 1 ' Using ListView1.Items.Count to get max number of rows to prevent error ' Highlight each item For index As Integer = 0 To count ListView1.Items(index).Selected = True ' First Selected Item If index = 0 Then For Each item As ListViewItem In ListView1.SelectedItems OpenModule.TextBox1.Text = item.Text OpenModule.TextBox2.Text = item.SubItems(1).Text Next End If ' Second Selected Item If index = 1 Then For Each item As ListViewItem In ListView1.SelectedItems OpenModule.TextBox3.Text = item.Text OpenModule.TextBox4.Text = item.SubItems(1).Text Next End If ' Third Selected Item If index = 2 Then For Each item As ListViewItem In ListView1.SelectedItems OpenModule.TextBox5.Text = item.Text OpenModule.TextBox6.Text = item.SubItems(1).Text Next End If ' Forth Selected Item If index = 3 Then For Each item As ListViewItem In ListView1.SelectedItems OpenModule.TextBox7.Text = item.Text OpenModule.TextBox8.Text = item.SubItems(1).Text Next End If ' Fith Selected Item If index = 4 Then For Each item As ListViewItem In ListView1.SelectedItems OpenModule.TextBox9.Text = item.Text OpenModule.TextBox10.Text = item.SubItems(1).Text Next End If ' Sixth Selected Item If index = 5 Then For Each item As ListViewItem In ListView1.SelectedItems OpenModule.TextBox11.Text = item.Text OpenModule.TextBox12.Text = item.SubItems(1).Text Next End If ' Seventh Selected Item If index = 6 Then For Each item As ListViewItem In ListView1.SelectedItems OpenModule.TextBox13.Text = item.Text OpenModule.TextBox14.Text = item.SubItems(1).Text Next End If ' Eighth Selected Item If index = 7 Then For Each item As ListViewItem In ListView1.SelectedItems OpenModule.TextBox15.Text = item.Text OpenModule.TextBox16.Text = item.SubItems(1).Text Next End If ' Ninth Selected Item If index = 8 Then For Each item As ListViewItem In ListView1.SelectedItems OpenModule.TextBox17.Text = item.Text OpenModule.TextBox18.Text = item.SubItems(1).Text Next End If ' Tenth Selected Item If index = 9 Then For Each item As ListViewItem In ListView1.SelectedItems OpenModule.TextBox19.Text = item.Text OpenModule.TextBox20.Text = item.SubItems(1).Text Next End If ' Deselect Current Item ListView1.Items(index).Selected = False Next 方法:

__init__

这样:

import collections
class AnswerDict2(collections.UserDict):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        for key in kwargs:
            self[key] = 42

将输出:

ad = AnswerDict2(a="foo")
print(ad)