首页 > IT职业 > IT图书 > python修改属性值有哪些方法

1、直接修改属性值
修改属性值最简单的方法就是通过实例直接访问。
class Cat():
def __init__(self, name, color):
self.name = name
self.color = color
self.age = 3
def eat(self):
print('cat ' + self.name + ' color ' + self.color + ', now eat')
def run(self):
print('cat ' + self.name + ' color ' + self.color + ', now run')
def print_age(self):
print('cat`s age is ' + str(self.age))
my_cat = Cat('Spring', 'white')
my_cat.print_age()
my_cat.age = 4
my_cat.print_age()
2、用方法修改属性值
再次更新代码,添加update_age()方法来修改age属性。
class Cat():
def __init__(self, name, color):
self.name = name
self.color = color
self.age = 3
def eat(self):
print('cat ' + self.name + ' color ' + self.color + ', now eat')
def run(self):
print('cat ' + self.name + ' color ' + self.color + ', now run')
def print_age(self):
print('cat`s age is ' + str(self.age))
def update_age(self, age):
self.age = age
my_cat = Cat('Spring', 'white')
my_cat.print_age()
my_cat.update_age(10)
my_cat.print_age()
以上就是python类属性设置默认值的方法,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1775/viewspace-2830141/ ,如需转载,请注明出处,否则将追究法律责任。