+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

当我尝试使用类广告继承时,其中一些属性设置为未定义

发布于2021-01-17 16:24     阅读(820)     评论(0)     点赞(4)     收藏(0)


0

1

2

3

4

5

6

7

8

9

当我尝试运行此代码时:

class Person:

    def __init__(self, name, age, height):
        self.name = name
        self.age = age
        self.height = height

    def __str__(self):
        return "Name: {}, Age: {}, Height: {}".format(self.name, self.age, self.height)

    def get_older(years):
        self.age += years

class Worker(Person): 

    def __init__(self, name, age, height, salary):
        super(Worker, self).__init__(name, age, height)
        self.salary = salary 

    def calc_yearly_salary(self):
        return salary * 12

worker1 = Worker('Henry', 42, 178, 3350)
print(worker1)
print(worker1.calc_yearly_salary())

它无法识别工资属性,因此出现以下错误,提示“工资”未定义:

runfile('C:/Users/Jorge87/Desktop/Master Tema 1.5/inheritance_practice.py', 
wdir='C:/Users/Jorge87/Desktop/Master Tema 1.5')
Name: Henry, Age: 42, Height: 178
Traceback (most recent call last):

File "<ipython-input-11-07b76e08cf24>", line 1, in <module>
runfile('C:/Users/Jorge87/Desktop/Master Tema 1.5/inheritance_practice.py', 
wdir='C:/Users/Jorge87/Desktop/Master Tema 1.5')

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 
827, in runfile
execfile(filename, namespace)

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 
110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/Jorge87/Desktop/Master Tema 1.5/inheritance_practice.py", line 32, in <module>
print(worker1.calc_yearly_salary())

File "C:/Users/Jorge87/Desktop/Master Tema 1.5/inheritance_practice.py", line 28, in 
calc_yearly_salary
return salary * 12

NameError: name 'salary' is not defined

我的代码有什么问题?另外,它似乎无法识别定义的变量“ get_older(years)”中的“ years”属性


解决方案


在您的Worker课程中,您需要使用而不是来引用salary属性self.salarysalary

def calc_yearly_salary(self):
    return self.salary * 12

0

1

2

3

4

5

6

7



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接: https://www.pythonheidong.com/blog/article/777230/df077c57cf6ac40c499c/

来源: python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

4 0
收藏该文
已收藏

评论内容:(最多支持255个字符)