我想知道这种创建单身的方法是否正确。
Public Class Form1
Dim outputs As List(Of Output) ' this holds the fake output data.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Replace this section with the code to retrieve stations from database.
Dim stations As New List(Of Station) From {
New Station() With {.StationName = "Station 1"},
New Station() With {.StationName = "Station 2"}
}
' Add stations to first combobox
Dim firstColumn = New DataGridViewComboBoxColumn()
For Each station In stations
firstColumn.Items.Add(station.StationName)
Next
' Populate fake data, replace this section with the code to retrive outputs from database.
outputs = New List(Of Output) From {
New Output() With {.OutputName = "OutP1", .StationName = "Station 1"},
New Output() With {.OutputName = "OutP2", .StationName = "Station 1"},
New Output() With {.OutputName = "OutP5", .StationName = "Station 2"},
New Output() With {.OutputName = "OutP6", .StationName = "Station 2"},
New Output() With {.OutputName = "OutP7", .StationName = "Station 2"}
}
' add combobox columns to datagridview
DataGridView1.Columns.Add(firstColumn)
DataGridView1.Columns.Add(New DataGridViewComboBoxColumn())
End Sub
Private Sub DataGridView1_CellBeginEdit(sender As Object, e As DataGridViewCellCancelEventArgs) Handles DataGridView1.CellBeginEdit
' Only process if the column is the second combobox.
' You will need to change the index according to your second combobox index.
' e.ColumnIndex = 1 because the second combobox index is 1 in this sample.
If e.ColumnIndex = 1 Then
' Filter the outputs by selected Station in the row.
' Change the ColumnIndex to your first combobox index.
' DataGridView1(0, e.RowIndex) because the first combobox index is 0 in this sample.
Dim outputByStation = outputs.Where(Function(x) x.StationName = DataGridView1(0, e.RowIndex).Value.ToString())
' Get current cell, we're going to populate the combobox
Dim currentCell = CType(DataGridView1(e.ColumnIndex, e.RowIndex), DataGridViewComboBoxCell)
' Populate the cell's combobox.
currentCell.Items.Clear()
For Each output In outputByStation
currentCell.Items.Add(output.OutputName)
Next
End If
End Sub
End Class
Public Class Station
Public Property StationName As String
End Class
Public Class Output
Public Property OutputName() As String
Public Property StationName() As String
End Class
my_class.py
另一个模块:
class MyClass(object):
def a_method(self):
print("Hello World")
...
MY_CLASS_SINGLETON = MyClass()
所以这段代码对我有用,但我的疑问是垃圾收集器是否可以在任何其他模块使用之前销毁from my_class import MY_CLASS_SINGLETON
if __name__ == "__main__":
MY_CLASS_SINGLETON.a_method()
实例,因为最后它只是MY_CLASS_SINGLETON
中的一个临时变量{1}}模块。
答案 0 :(得分:0)
我认为你的实现不是一个保存单例,只要你可以轻松创建MyClass的新实例。单例应该通过自己保持这个实例并且只返回这个实例来避免这种情况 - 你的实例是在类之外保存的。 (但我自己是Python的新手,而且我只是维护程序编写的Python代码。)
但你看了here吗?