python中@property

本文介绍Python中如何使用@property装饰器来管理类的属性,并提供了列表、元组及字典的基本操作示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • @property将类中的属性变为私有的(类似于java中的private)
  • @property使方法像属性一样调用,就像是一种特殊的属性
class C:
    def __init__(self):
        self._x = 5

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    # @x.setter
    # def x(self, value):
    #     self._x = value
    #
    # @x.deleter
    # def x(self):
    #     del self._x
c = C()

print(c.x)
复制代码
  • 列表、字典、元组
#list

"""
list1 = ['Google', 'Runoob', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];
#删除列表元素
del list2[0]
list2.remove(3)
list4 = list2+list3
print(list4)
list4.clear()
print(list4)
list4.append(2)
ret = list4.is_empty()
list
print(ret)
print(list4)
print(list1[1:3])#取前不取后
print(list2)
"""

#tup
#元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用

tup1 = (50)
print(type(tup1))     # 不加逗号,类型为整型
tup1 = (50,)
print(type(tup1))     # 加上逗号,类型为元组


#字典
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}


dict.update({'fengfeng':'吃饭'})
print(dict)

del dict['Name'] # 删除键 'Name'
dict.clear()     # 清空字典
del dict         # 删除字典

# print ("dict['Age']: ", dict['Age'])
# print ("dict['School']: ", dict['School'])
#因为用执行 del 操作后字典不再存在

复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值