当我在 init 中调用类方法(在其中初始化对象)时,每次都会调用类方法 count_genre ,从而递增之前的值。我只想调用该方法一次。
class Furniture:
materials = []
material_count = {}
def __init__(self, name, material):
self.name = name
self.material = material
Furniture.materials.append(self.material)
Furniture.count_material()
@classmethod
def count_material(cls):
for material in cls.materials:
cls.material_count[material] = cls.material_count.get(material, 0) + 1
Furniture("Chair", "Wood")
Furniture("Cushion", "Cotton")
Furniture("Table", "Glass")
print(Furniture.material_count)
这是我在终端上得到的信息: {“椅子”:3,“垫子”:2,“桌子”:1}
这就是我想要得到的: {“椅子”:1,“垫子”:1,“桌子”:1}
使用
Furniture
为一件家具建模。使用单独的类来对一组特定家具的信息进行建模。
import dataclass
import collections
@dataclasses.dataclass
class Furniture:
name: str
material: str
class FurnitureCollection:
def __init__(self):
self.material_count = collections.Counter()
self.pieces = []
def add(self, f: Furniture):
self.pieces.append(f)
self.material_count[f.material] += 1
@property
def materials(self):
return list(self.material_count)
fc = FurnitureCollection()
fc.add(Furniture("Char", "Wood"))
fc.add(Furniture("Cushion", "Cotton"))
fc.add(Furniture("Table", "Glass"))
assert fc.material_count["Wood"] == 1
assert all(x in fc.materials for x in ["Wood", "Cotton", "Glass"])