# 实例属性的get和set方法
class Student:
def __init__(self,name: str,age: int):
self.name = name
self.__age = age
def __str__(self):
return f"{self.name},{self.__age}"
def set_age(self,age: int):
if age < 0 or age > 150:
raise Exception(f"Age{age} is not valid")
self.__age = age
def get_age(self):
return self.__age
# age = property(fget=get_age,fset=set_age)
student = Student("xiaoming",19)
student.set_age(10)
student.age = 4 # 因为python是动态语言,如果没有使用property类的话,只是给类重新定义一个color属性,并不是给__color私有属性赋值
print(student.age) # 打印结果是4
print(student.get_age()) # get方法取到的结果是10,是从私有属性中取得的
print(student)
# @property装饰器的使用
class Car:
def __init__(self,brand: str,color: str):
self.brand = brand
self.__color = color
@property
def color(self):
return self.__color
@color.setter
def color(self,color: str):
if color == "红色":
raise Exception("这个颜色禁止使用")
self.__color = color
def __str__(self):
return f"{self.__color}的{self.brand}在路上跑"
c1 = Car("benz","蓝色")
c1.color = "白色"
print(c1)
python 私有属性的get和set方法,@property装饰器的使用
最新推荐文章于 2024-07-12 16:16:27 发布