繁体   English   中英

在Python中初始化子类变量

[英]Initializing subclass variable in Python

在这里,我有一个示例代码来测试python类的继承。
在这里,基类是'Person','Employee'继承了基类-'Person'。 另外,继承人类'Employee'还有2个子类。 我想在子类-'OfficeWorker'和'ProductionWorker'中初始化子类veriables,但是我得到了'TypeError:__init __()接受2个位置参数,但给出了7个位置参数'。 需要pyhton专家建议在此处定义和初始化子类变量并更正我的代码

<snip of error>

#$ ./employee86253.py
Enter the name: sunnily
Enter the address: 41801
Enter the phone: 345
Enter the ID number: 12
Enter the employee type ('S' for salaried or 'H' for hourly): S
Enter the skill type ('eng', 'acc', 'sales', 'mgr'): eng
Enter the monthly salary: 123
Traceback (most recent call last):
  File "./employee86253.py", line 110, in <module>
    main ()
  File "./employee86253.py", line 78, in main

**ERROR:**

    **worker = OfficeWorker(worker_name, worker_address, worker_phone, worker_id,  skill_type, salary)
TypeError: __init__() takes 2 positional arguments but 7 were given**

================== script =======================

#!/usr/bin/env python

# Base class
class Person:
   def __init__ (self, name, address, phone_number):
         self.name = name
         self.address = address
         self.phone_number = phone_number

   def get_name(self):
        return self.name

   def get_address(self):
        return self.adress

# subclass, inheriting class - Person
**class Employee (Person):
   def __init__(self, id_number):
        Person.__init__(self, name, address, phone_number)
        self.id_number = id_number**

   def get_id_number(self):
        return self.id_number

# sub class, inheriting Class - Employee       
class ProductionWorker (Employee):
   **def __init__(self, shift_number, pay_rate):
        super().__init__(id_number)
        self.shift_number = shift_number
        self.pay_rate = pay_rate**

   def get_shift_number ( self ):
        return self.shift_number

   def compute_pay_for_hours( self, hours):
        minutes = hours * 60
        return  ( minutes  * self.pay_rate ) / minutes

   def get_pay_rate(self ):
         return self.pay_rate

# Subclass, inheriting class - Employee    
class OfficeWorker (Employee):
   **def __init__(self, skill_type, monthly_salary):
        super().__init__(id_number)
        self.skill_type = skill_type
        self.monthly_salary = monthly_salary**

   def get_skill_type(self):
        return self.skill_type

   def compute_pay_for_weeks(self, weeks):
        return  (weeks * self.monthly_salary ) /  4 


   def get_month_salary( self ):
        return self.monthly_salary


def main():
    # Local variables
    worker_name= ''
    worker_id = ''
    worker_shift = 0
    worker_pay = 0.0
    skill_type = ''
    salary = 0.0
    emp_type = 'P'
    **# Get data attributes
    worker_name = input('Enter the name: ')
    worker_address = input('Enter the address: ')
    worker_phone = input('Enter the phone: ')
    worker_id = input('Enter the ID number: ')
    emp_type = input('Enter the employee type (\'S\' for salaried or \'H\' for hourly): ')
    if emp_type == 'S':
        skill_type = input('Enter the skill type (\'eng\', \'acc\', \'sales\', \'mgr\'): ')
        salary = float(input('Enter the monthly salary: '))
        worker = OfficeWorker(worker_name, worker_address, worker_phone, worker_id,  skill_type, salary)
    elif emp_type == 'H':
        worker_shift = int(input('Enter the shift number: '))
        worker_pay = float(input('Enter the hourly pay rate: '))
        worker = ProductionWorker(worker_name, worker_address, worker_phone, worker_id,  worker_shift, worker_pay)
    else:
        print('Invalid employee type')
        return**

    # Create an instance of ProductionWorker


    # Display information
    print ('Employee information:')
    print ('Name:', worker.get_name())
    print ('Address:', worker.get_address())
    print ('Phone:', worker.get_phone())
    print ('ID number:', worker.get_id_number())
    if isinstance(worker,ProductionWorker):
        print ('Shift:', worker.get_shift_number())
        print ('Hourly Pay Rate: $', \
           format(worker.get_pay_rate(), ',.2f'), sep='')
        print ('Pay Amount for 5.2 hours: $', \
           format(worker.compute_pay_for_hours(5.2), ',.2f'), sep='')
    else:
        print ('Skill type:', worker.get_skill_type())
        print ('Monthly Salary: $', \
           format(worker.get_month_salary(), ',.2f'), sep='')
        print ('Pay Amount for 2.5 months: $', \
           format(worker.compute_pay_for_weeks(10), ',.2f'), sep='')

# call the main function
main ()

以最简单的情况为例(但是到处都有它的克隆):

def __init__(self, id_number):
    Person.__init__(self, name, address, phone_number)

您认为name, address, phone_number将从何而来 如果应该将它们作为对Employee调用的参数,则必须将其作为__init__参数列出(并根据需要从其他子类“传递给它”)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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