【问题标题】:Confusion with classes and global variables混淆类和全局变量
【发布时间】:2016-07-31 15:19:29
【问题描述】:

我的第一个项目的制作已经停止。我正在尝试制作一个考勤卡程序。我决定使用类对象在本地处理变量,但我不知道如何从用户输入中创建类对象。

import time
import datetime
import sqlite3

class Employee(object):
    def __init__(self, name, position, wage=0, totalpay=0, totalhours=0):
        self.name = name
        self.position = position
        self.wage = wage
        self.totalpay = totalpay
        self.totalhours = totalhours

    def HourlyPay(self):
        if self.position not in range(1, 4):
            return "%s is not a valid position" % self.position
        elif self.position == 1:
            self.wage = 105.00
        elif self.position == 2:
            self.wage = 112.50
        elif self.position == 3:
            self.wage = 118.50
        return "%s at position %i is making %i DKK per hour" % (self.name, self.position, self.wage)


    def Salary(self, hours):
        self.hours = hours
        self.totalpay += self.wage * self.hours
        self.totalhours += self.hours
        return "%s next salary will be %i DKK" % (self.name, self.totalpay)

# This is out Employee object
EmployeeObj = Employee('John Doe', 1) # Our Employee object
EmployeeObj.HourlyPay()
EmployeeObj.Salary(43) # Takes 'hours' as argument


# Temporary Database config and functions below
conn = sqlite3.connect('database.db')
c = conn.cursor()

# For setting up the database tables: name, position and total.
def Create_table():
    c.execute('CREATE TABLE IF NOT EXISTS EmployeeDb(name TEXT, position INTEGER, total REAL)')

# Run to update values given by our Employee object
def Data_entry():
    name = str(EmployeeObj.name)
    position = int(EmployeeObj.position)
    total = float(EmployeeObj.totalpay)
    c.execute('INSERT INTO EmployeeDb (name, position, total) VALUES (?, ?, ?)',
              (name, position, total))
    conn.commit()
    c.close()
    conn.close()
    return True

我想要实现的是从用户输入创建这个变量:

EmployeeObj = Employee('John Doe', 1) # Our Employee object

【问题讨论】:

    标签: class python-3.x variables input


    【解决方案1】:

    也许你可以这样做:

    name = input("Enter employee name:")
    position = int(input("Enter employee position:"))
    EmployeeObj = Employee(name, position)
    

    【讨论】:

      猜你喜欢
      • 2018-03-16
      • 1970-01-01
      • 2016-12-27
      • 1970-01-01
      • 1970-01-01
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多