直接修改属性的值
要修改属性的值,可以通过类的实例直接访问它。例如,下面代码中,通过句点表示法dog.weight = 20
修改了属性的值为20:
class Dog:
"""小狗类"""
def __init__(self, name, age, color):
"""初始化描述狗的属性"""
self.name = name
self.age = age
self.color = color
self.weight = 1
def get_description(self):
"""返回描述信息"""
description = f"{self.name} {self.age} {self.color}"
return description.title()
def read_weight(self):
"""打印重量信息"""
print(f"The dog's weight is {self.weight}")
# 创建一个狗的实例
dog = Dog('Shiwu', 3, 'white')
# 调用狗的方法
print(dog.get_description())
dog.weight = 20
dog.read_weight()
运行输出:
通过方法修改属性的值
有时候需要编写方法进行更新,这样就无须直接访问属性,而可将值传递给方法,由它在内部进行更新。
class Dog:
"""小狗类"""
def __init__(self, name, age, color):
"""初始化描述狗的属性"""
self.name = name
self.age = age
self.color = color
self.weight = 1
def get_description(self):
"""返回描述信息"""
description = f"{self.name} {self.age} {self.color}"
return description.title()
def read_weight(self):
"""打印重量信息"""
print(f"The dog's weight is {self.weight}")
def update_weight(self, weight):
"""将重量设置为指定的值"""
self.weight = weight
# 创建一个狗的实例
dog = Dog('Shiwu', 3, 'white')
# 调用狗的方法
print(dog.get_description())
dog.update_weight(20)
dog.read_weight()
运行输出:
在上面类中,定义了一个方法update_weight(self, weight)
,这个方法接受一个重量值,并将其赋给self.weight
。
通过方法对属性的值进行递增
有时候需要将属性的值递增特定的量,而不是将其设置为全新的值。例如:
class Dog:
"""小狗类"""
def __init__(self, name, age, color):
"""初始化描述狗的属性"""
self.name = name
self.age = age
self.color = color
self.weight = 1
def read_weight(self):
"""打印重量信息"""
print(f"The dog's weight is {self.weight}")
def update_weight(self, weight):
"""将重量设置为指定的值"""
self.weight = weight
def increment_weight(self, weight):
"""将重量增加指定的量"""
self.weight += weight
# 创建一个狗的实例
dog = Dog('Shiwu', 3, 'white')
# 调用狗的方法
dog.update_weight(20)
dog.read_weight()
dog.increment_weight(5)
dog.read_weight()
运行输出: