简体   繁体   中英

Is this the correct approach to build 'super structure' classes in Python?

I am trying to build a class that I can use to instantiate new work projects from. The idea is that each project will call upon resources from different departments and I need to be able to implement if needed- within the Project object. Each Department should be able to access project-level attributes and methods, as well as the project object being able to access individual departments attributes (ie for summing departmental costs to return overall project cost).

Below is some pseudo code of what I am trying to do and would appreciate any guidance on what the correct approach would be:

Define the project

class Project:
    totalCost=0

    def addDepartment(Dept):
        totalCost+=name.DepartmentCost
        Departments=append(Dept)

Define the department(s)

class Department1:
    def __init__(self,Name, NumStaff, AverageStaffSalary)
    Name=None
    NumStaff=None
    AverageStaffSalary=None
    DepartmentCost=AverageStaffSalary*NumStaff
    Department1_SpecificParm=1


class DepartmentN:
    def __init__(self,Name, NumStaff, AverageStaffSalary)
    Name=None
    NumStaff=None
    AverageStaffSalary=None
    DepartmentCost=AverageStaffSalary*NumStaff
    DepartmentN_SpecificParm="A"

Instantiate project and nested departments within it

p1=Project("myProject")
p1.addDepartment(Department1(Name="myFirstDepartment", NumStaff=9, AverageStaffSalary=1000))
print p1.myFirstDepartment.DepartmentCost        #Print 9000

p1.addDepartment(DepartmentN(Name="myNthDepartment", NumStaff=2, AverageStaffSalary=6000))
print p1.myNthDepartment.DepartmentCost        #Print 12000

Return total cost across all departments

p1.TotalCost          #Print 21000  

(Posting answer provided in comments)

Your code doesnt make much sence (even for psudo code) but i think this could be along the lines of what you are looking for. Repl.it playground

class Project:
  total = 0
  deps = []

  def addDep(self, dep):
    self.total += dep.cost
    self.deps.append(dep)

class Department:
  def __init__(self, ppl, salary):
    self.cost = ppl * salary

p = Project()
p.addDep(Department(10, 200))
p.addDep(Department(1, 3000))

print(p.total)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM