Python硬件,类和方法有问题

2024-04-26 13:22:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我在CS课上遇到了硬件问题。这个问题与在python中创建类有关。这是提示

您的类应该命名为Student,并且您应该定义以下方法:

__init__:此方法初始化Student对象。在

参数:一个名字,一个平均绩点,和一些单位采取

•应根据 传来的信息。如果GPA或单位数为负数,则将其设置为0。(在这种方法中,不必担心非数值。)

update:如果学生接受一个新的类,这个方法更新Student对象的实例变量。在

•参数:新班级的单位、新班级获得的分数(以数字表示)。在

•应修改units的实例变量以添加新类的单位

•应修改GPA,以纳入新班级的成绩。(请注意,这将是使用单位计数和两组GPA的加权平均值。)

get_gpa:此方法应返回学生的gpa。在

get_name:此方法应返回学生的姓名。在

这是我拥有的

class Student:
  def__init__(self,name,GPA,units):
    if units <0:
      units=0
    if GPA<0:
      GPA=0
    self.name=name
    self.GPA=GPA
    self.units=units

  def update(newunits,GPE):

我能想到的就这些


Tags: 对象实例方法nameself参数getinit
2条回答

让我们来回顾一些有助于您的要点:

构造函数(__init__

If the GPA or number of units is negative, sets it to 0.

所以您可能需要分别检查:

if units < 0:
    units = 0
if GPA < 0:
    GPA = 0

更新方法

方法通常将对当前对象的引用作为第一个参数,按照约定命名为self(就像在__init__中一样)。所以您的update方法声明应该如下所示:

^{pr2}$

Should modify the instance variable for units to add the units for the new class

正如您在构造函数中所做的那样,您可以使用self.varname访问实例变量。所以你可能想做这样的事情:

self.units += newunits

Should modify the GPA to incorporate the grade earned in the new class. (Note that this will be a weighted average using both the unit counts and both sets of GPAs.)

就像你更新self.units一样,你必须在这里更新self.GPA。不幸的是,我不知道什么是GPA以及它是如何计算的,所以我只能猜测:

self.GPA = ((self.GPA * oldunits) + (GPE * newunits)) / self.units

注意,我在这里引入了一个新的局部变量oldunits,它只是在更新之前临时存储来自的单元(因此在更新之后oldunits = self.units - newunits)。在

获得gpa并获得\ u name

这些是简单的getter,只从对象返回一个值。这里有一个单位的例子,也就是说,你应该自己计算出实际想要的值:

def get_units (self):
    return self.units

请注意,使用getter(get_x方法)是相当不和谐的,因为您只希望人们直接访问属性(同时小心地处理它们)。在

我会帮你完成这道题,但让我先指出一个小错误:

if units <0 and GPA <0:
  units=0
  GPA=0

只有当单位和GPA都为负数时,才会将它们设置为零。如果是负数,则需要将每个值设置为零,即使另一个不是。更改为:

^{pr2}$

关于您的更新方法,正确的签名应该是:

def update(self, newunits, GPE):

Python对象方法应该始终以self开头。在

现在,我不确定如何计算GPA(如果我还活着的话,我们使用不同的系统),但是根据一些相当谷歌的查询,你的更新方法应该是:

def update(self, newunits, GPE):
    GPE_earned_before = self.GPA * self.units
    total_GPE = GPE_earned_before + GPE
    self.GPA = total_GPE / (self.units + newunits)
    self.units += newunits

我在这里使用了很多变量来说明问题,但这可以简化为:

def update(self, newunits, GPE):
    self.GPA = (self.GPA * self.units + GPE) / (self.units + newunits)
    self.units += newunits

相关问题 更多 >