定义实例属性修改提示只读?

定义实例属性修改提示只读?

问题描述

学习Python仅半个月,写了一个简单的时钟程序,可实现计时或显示本地时间。
在实例化运行时提示:
AttributeError: 'Clock' object attribute 'seconds' is read-only

问题出现的环境背景及自己尝试过哪些方法

版本:3.7
把能试的办法都试过了,检查不出这个bug

相关代码

import time

from copy import deepcopy

from os import system

class Clock(object):

__slots__ = ('hours', 'minutes', 'seconds', '_years', '_months', '_days')

def __init__(self, hours=0, minutes=0, seconds=0, years=0, months=0, days=0):

self.hours = hours

self.minutes = minutes

self.seconds = seconds

self._years = years

self._months = months

self._days = days

@property

def year(self):

return self._years

@property

def month(self):

return self._months

@property

def day(self):

return self._days

@year.setter

def year(self, years):

self._years = years

@month.setter

def month(self, months):

self._months = months

@day.setter

def day(self, days):

self._days = days

@classmethod

def change(cls):

# 获取本地时间

cls._years = time.localtime()[0]

cls._months = time.localtime()[1]

cls._days = time.localtime()[2]

cls.hours = time.localtime()[3]

cls.minutes = time.localtime()[4]

cls.seconds = time.localtime()[5]

def judgement(self):

# 判断平年闰年

leap_year = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

non_leap_year = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

if not (self._years % 4):

this_year = deepcopy(leap_year)

else:

this_year = deepcopy(non_leap_year)

return this_year

def run(self):

# 时钟

if self._days == 0 or self._months == 0 or self._days == 0:

Clock().change()

while True:

self.seconds += 1

if self.seconds == 60:

self.minutes += 1

self.seconds = 0

if self.minutes == 60:

self.hours += 1

self.minutes = 0

if self.hours == 24:

self._days += 1

self.hours = 0

this_year = Clock().judgement()

if self._days == this_year[self._months + 1]:

self._months += 1

self._days = 0

if self._months == 12:

self._years += 1

self._months = 0

print('%04d.%02d.%02d %02d:%02d:%02d' % (self._years, self._months, self._days,

self.hours, self.minutes, self.seconds))

time.sleep(1)

system('cls')

a = Clock()

a.run()


回答:

我试了一下, 如果在设置了__solts__的情况下, 先修改同名类属性, 再修改实例属性 就会报错, 如:

a = Clock()
Clock.seconds = 1
a.seconds = 2

去掉__solts__,或者把你的本地时间存到别的地方去。

以上是 定义实例属性修改提示只读? 的全部内容, 来源链接: utcz.com/a/162267.html

回到顶部