如何在Whatsleet(self)下分别访问变量日和年的数据:

2024-10-02 12:30:41 发布

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

我有下面的类,在第一个方法上简单地输入数据。然后,我只需添加其他方法来与它们交互。我正在学习面向对象编程:)我的问题是我不知道如何在Whatsleet(self):方法下访问天数和年份的值。我知道如何使用返回码获取它们的值,但不是单独获取

我总是会遇到这样的错误: 文件“/className.py”,第44行,在 打印n.whatsleet.days() AttributeError:“函数”对象没有属性“天”

class dude():

    def getDudeInfo(self, name, age, job, jobDuration):
        self.name = name
        self.age = age
        self.job = job
        self.jobDuration = jobDuration

    def getAgeDays(self):
        x = self.age*356
        return x

    def getRetire(self):
        x = 59-self.age
        return x

    def daysByRetire(self):
        x = self.getAgeDays() + self.getRetire()*356
        return x

    def whatsLeft(self):
        days = 35600 - self.daysByRetire()
        years = days / 356
        return "{} or {} years left to live".format(days, years)

Tags: 数据方法nameselfagereturndefjob
1条回答
网友
1楼 · 发布于 2024-10-02 12:30:41

导致您的错误的原因与此类似(因为您的回溯):

class Dude:
    # same as before
    def whatsLeft(self):
        days = 35600 - self.daysByRetire()
        years = days / 356
        return "{} or {} years left to live".format(days, years)

# n = Dude()
print n.whatsLeft.days()

不能直接在函数外部访问whatsLeftdaysyears。您可以将daysyears更改为实例属性

class Dude:
    # same as before
    def whatsLeft(self):
        self.days = 35600 - self.daysByRetire()
        self.years = days / 356
        return "{} or {} years left to live".format(self.days, self.years)

# n = Dude()
n.whatsLeft()
print n.days()

或者返回daysyears而不是字符串

class Dude:
    # same as before
    def whatsLeft(self):
        days = 35600 - self.daysByRetire()
        years = days / 356
        return days, years

# n = Dude()
print n.whatsLeft()[0]

相关问题 更多 >

    热门问题