【问题标题】:How to access values in a class?如何访问类中的值?
【发布时间】:2021-02-07 15:54:14
【问题描述】:

我创建了一个类,我想从中访问一些值。这是类的样子:

class County:
  def __init__(self, init_name, init_population, init_voters) :
    self.name = init_name
    self.population = init_population
    self.voters = init_voters

还有一个我想实现的功能。

def highest_turnout(data) :
    turnout = (self.voters / self.population) / 100

    return #I haven't completed what I need to do

因为我想从函数 1 中访问值,所以我将第二个函数放在该类中以访问这些值。但是,我开始在代码的下方收到 ​​NameError。

result = highest_turnout(data) #this is the name of my function
#this is the error I get
NameError: name 'highest_turnout' is not defined

所以我的问题是,我真的需要将第二个函数放入类中才能访问这些值吗?如果需要,为什么会出现此错误?如何解决?

【问题讨论】:

  • County(....data...).highest_turnout(data) ?

标签: python function class nameerror


【解决方案1】:

假设我们有这个类。

class County:
    def __init__(self, init_name, init_population, init_voters):
        self.name = init_name
        self.population = init_population
        self.voters = init_voters

然后我们如下构造它的值。

data = Country(...)

现在,类内部的实例名称为self(至少在惯用语中如此),因此如果您在类中有一个实例方法,则使用self 来引用它.但是如果你定义一个独立函数,它接受一个名为data 的参数,那么你使用data 来引用它,而不是self

# NOT in the class
def highest_turnout(data):
    turnout = (data.voters / data.population) / 100

highest_turnout(data)

如果您确实希望它出现在课堂上,那么您可以按照以下方式进行。

# In the class
def highest_turnout(self):
    turnout = (self.voters / self.population) / 100

data.highest_turnout()

【讨论】:

  • 我将第二个函数放在类之外,但出现此错误:AttributeError: 'list' object has no attribute 'voters'
【解决方案2】:

您必须将self 作为参数添加到您的方法中才能访问类字段,它还必须与您的类构造函数处于相同的缩进级别,如下所示:

class County:
  def __init__(self, name, population, voters) :
    self.name = name
    self.population = population
    self.voters = voters

  def highest_turnout(self, data) :
    turnout = (self.voters / self.population) / 100

    return #I haven't completed what I need to do

还有谁告诉你在 init 函数中为所有参数添加前缀 init_ 那是有用的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多