题解 | #修改属性2#

修改属性2

https://www.nowcoder.com/practice/7831806be5684ad6ac0f8b43e3e3558e

class employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def printclass(self):
        print(f"{self.name}'salary is {self.salary}, and his age is {self.age}")

name = input()
salary = input()
age = input()
e = employee(name, salary)
print(hasattr(e, age))
if hasattr(e, 'age'):
    e.printclass()
else:
    setattr(e, "age", age)
    e.printclass()

setattr() 函数对属性进行赋值:

setattr(object, name, value)

如果属性是已经存在的用单引号,如果是未存在的,需要先创建再赋值,这时需要用双引号

hasattr(object, name)判断一个对象里面是否有name属性或者name方法,返回BOOL值,有name特性返回True, 否则返回False。
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务