Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ChoiceField(object): #
- choices = ['offline','hidden','online','mage','assasin','knight','warrior']
- val = ''
- def __init__(self, val):
- self.choices = __class__.choices
- self.val = val
- def __get__(self, instance, owner):
- return self.val
- '''__get__(self, instance, instance_class)
- Определяет поведение при возвращении значения из дескриптора. instance это объект,
- для чьего атрибута-дескриптора вызывается метод. owner это тип (класс) объекта.
- '''
- def __set__(self, instance, val):
- '''__set__(self, instance, value)
- Определяет поведение при изменении значения из дескриптора.
- instance это объект, для чьего атрибута-дескриптора вызывается метод.
- value это значение для установки в дескриптор. '''
- if val in self.choices:
- self.val = val
- else:
- raise ValueError('Invalid value(profa or status)')
- class Hero(object):
- profession = ['mage','assasin','knight','warrior']
- # status = ['offline','hidden','online']
- name = ''
- level = ''
- location = "23.44344, 0.344234"
- profa = ChoiceField('profa') #descriptor
- character_status = ChoiceField('character_status') #проверяем такущий статус героя #descriptor
- def __init__(self, character_status,profa,name,level, location):
- self.character_status = character_status #descriptor
- self.profa = profa #descriptor
- self.name = self.validate_name(name)
- self.level = self.validate_level(level)
- self.location = self.validate_location(location)
- def validate_name(self, name):
- if isinstance(name, str) and name[0].isdigit() == False:
- return name
- else:
- raise ValueError('Invalid Name')
- def validate_level(self,level):
- if isinstance(level,(int, str)) == False and level.isalnum() == True and level.isdigit() == False :
- raise ValueError('level must be only int')
- elif int(level) >= 100:
- raise ValueError('out of range')
- else:
- return level
- def validate_location(self, location):
- x = location.split(',')
- if float(x[0]) and float(x[1]):
- return location
- else:
- raise ValueError('Erorr . invalid location')
- def save_to_file(self,data_file):
- with open(data_file, 'w') as write_file:
- s_data = json.dump((unit.__dict__,{"status": Hero.status,"profession": Hero.profession}), write_file, indent=4, separators=(',', ':'))
- return s_data
- def load_from_file(self,data_file):
- with open(data_file) as load_file:
- data = json.load(load_file)
- self.name = self.validate_name(data['name'])
- self.level = self.validate_level(data['level'])
- self.profa = self.validate_profession(data['profa'])
- self.location = self.validate_location(data['location'])
- self.character_status = self.validate_status(data['character_status'])
- data_file = 'hero.json'
- unit = Hero('online','mage','Sam','33','23.44344, 0.344234',)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement