面向对象高级特性之--__slots__限制对象属性

1.动态语言与静态语言的不同

动态语言:可以在运行的过程中,修改代码
静态语言:编译时已经确定好代码,运行过程中不能修改

2.slots

python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性
使用__slots__时注意: __slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的

import time
class Date(object):
    #__slots__来限制该对象能添加的属性信息,,即除了显示的年、月、日,不可以再添加时间属性,否则报错
    __slots__ = '__year','__month','__day'
    def __init__(self, year,month,day):
        self.__year=year    #不用new是因为自动将父类的new方法继承过来,自动实例化对象
        self.__month=month
        self.__day=day

    @property   #类属性
    def year(self):
        return self.__year
    @property
    def month(self):
        return self.__month
    @property
    def day(self):
        return self.__day
    @classmethod
    def today(cls):
        time_t=time.localtime()
        return cls(time_t.tm_year,time_t.tm_mon,time_t.tm_mday)
    def __str__(self):
        return '%s-%s-%s'%(self.__year,self.__month,self.__day)
"""
import time 获取当前时间的三种方法
time.localtime()-->tm_year=2020,tm_mon=1,tm_mday=5,tm_hour=15
time.time()--->1578208092.4181762
time.ctime()--->Sun Jan 5 15:08:16 2020
"""
d=Date(2019,10,10)
print('对象类型:',type(d))
print('判断是否有year这个属性?',hasattr(d,'year'))
print('判断是否有time这个属性?',hasattr(d,'time'))
#setattr(d,'time','10;10:10')
#print('time:',getattr(d,'time'))

print(Date.today())

结果

对象类型: <class '__main__.Date'>
判断是否有year这个属性? True
判断是否有time这个属性? False
2020-1-11
发布了36 篇原创文章 · 获赞 0 · 访问量 283

猜你喜欢

转载自blog.csdn.net/ANingL/article/details/103932955
今日推荐