会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132885个问题
Python 全系列/第一阶段:Python入门/序列 3571楼


'''定义一个 Employee 雇员类,要求如下:
(1) 属性有:id、name、salary
(2) 运算符重载+:实现两个对象相加时,默认返回他们的薪水和
(3) 构造方法要求:输入 name、salary,不输入 id。id 采用自增的方式,从 1000 开始自增,第一个新增对象是 1001,第二个新增对象是 1002
(4) 根据 salary 属性,使用@property 设置属性的 get 和 set 方法。set 方法要求输入:1000-50000 范围的数'''
class Employee:#定义一个雇员类
    id=1000#id从1000开始自增
    def __init__(self,name,salary):
        self.name=name
        self.__salary=salary
        Employee.id=Employee.id+1
    def __add__(self,other):
        if isinstance(other,Employee):
            return "薪水和:{}".format(other.__salary+self.__salary)
        else:
            return "同一对象,不能相加"

    @property
    def salary(self):
        return "顺序是:{0},名字是:{1},薪资是:{2}".format(Employee.id,self.name,self.__salary)

    @salary.setter
    def salary(self, salary):

        if 1000 < salary < 50000:
            self.__salary = salary

        else:
            print("输入错误!范围有误!!")


e1=Employee("王老大",2000)
print(e1.salary)
e2=Employee("王老二",20000)
print(e2.salary)
print(e1+e2)
e3=Employee("王老幺",200)
print(e3.salary)

老师,为什么我这个范围不对但是不返回范围有误

Python 全系列/第一阶段:Python入门/面向对象 3572楼
Python 全系列/第一阶段:Python入门/编程基本概念 3577楼

import turtle
class MyRectangle:

    def __init__(self,width = 100,height = 100,x = 0,y =0): #实例属性
        self.width = width
        self.height = height
        self.x = x
        self.y = y

    def getArea(self):#算面积,实例方法
        return (self.width * self.height)

    def getPerimeter(self):#算周长,实例方法
        return ((self.width + self.height) *2)

    def draw(self):         #画图像方法
        turtle.penup()
        turtle.goto(self.x, self.y)
        turtle.pendown()
        turtle.forward(self.width)
        turtle.left(90)
        turtle.forward(self.height)
        turtle.left(90)
        turtle.forward(self.width)
        turtle.left(90)
        turtle.forward(self.height)
        turtle.done()


s = MyRectangle()
print(s.getPerimeter())
print(s.getArea())
s.draw()

s = MyRectangle(200,10000,10,1)
print(s.getPerimeter())
print(s.getArea())
s.draw()

输出结果(乌龟图没有截图):截屏2020-08-24 上午11.35.51.png

问题:老师你好!我想问一下为什么我的输出结果只有两个结果,但是我一共调用了四次方法,前两个默认的数值被运用了,但是后面重新传参数的却没有输出结果。我的想法是,后面传参的新数值会覆盖原来默认的数值再跑一次程序,但是没有。麻烦老师能为我解释一下,谢谢!!

Python 全系列/第一阶段:Python入门/面向对象 3582楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637