class A:
def __init__(self, id, name ,age):
self.id = id
self.name = name
self.age = age
def get_id(self):
return self.id
def get_name(self):
return self.name
def get_age(self):
return self.age
class B:
def __init__(self, lst, file):
self.lst = lst
self.file = file
def writefile(self):
fileObj = open(self.file, 'w')
write_string = ''
for person in self.lst:
for func in [person.get_id, person.get_name, person.get_age]:
write_string = func() '\t'
write_string = write_string[:-1] '\n'
fileObj.write(write_string[:-1])
fileObj.close()
def main():
file = 'sample.txt'
def loadfile():
try:
filez = open(file, 'r')
except FileNotFoundError:
filez = open(file, 'w')
filez.close()
filez = open(file, 'r')
lst = []
for line in filez:
id, name, age = line.split('\t')
age = date.rstrip('\n')
lst.append(A(id, name, age))
return lst
population = loadfile()
call = B(population, file)
def add():
obj_A1 = A('1','bilal','29')
obj_A3 = A('3','asda','54')
population.append(obj_A1)
population.append(obj_A3)
add()
def display():
for i in population:
if i.get_id() == '3':
print('found')
display()
call.writefile()
main()
我是 OOP 的新手。我試圖了解將物件串列提供給 B 類是否會對它的關系產生任何影響。我希望這里的關系是 A 類和 B 類之間的聚合,如果我沒有錯,因為我將人口串列添加到 B 類?附言。對不起,長代碼。
uj5u.com熱心網友回復:
根據 Martin Fowler 的UML Distilled:
聚合是嚴格沒有意義的;因此,我建議您在自己的圖表中忽略它。
這給我們留下了一個問題,其中包含的物件是否與lst有關聯或組合關系B?
組合意味著正在組合的物件不會超過它們的容器類。這也意味著它們不被其他容器類共享。
關聯定義了比組合更松散的耦合關系,即一個物件僅參考另一個物件。在 python 中,這基本上轉化為類具有特定實體屬性的想法。
在您的代碼中,您首先實體化population然后將其傳遞給B的建構式。假設您有另一個C可以接收串列物件的物件,例如B:
class C:
def __init__(self, lst, file):
self.lst = lst
self.file = file
可以想象,稍后在您的main代碼塊中,population可以重用該變數來實體化C. 這將導致B和之間共享實體屬性C。此外,如果您del B稍后在代碼中的某個地方呼叫,它不會破壞population. 因此,您在這里只有一個關聯關系。
如果您想實作真正的組合(我假設這是聚合的意思),您可以在建構式中實體化串列:
class B:
def __init__(self, file):
self.lst = loadfile(file)
self.file = file
或者您可以在實體化時B實體化串列,如下所示:
call = B(loadfile(file), file)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/429033.html
