Instructions
Objective
Write a program to work on methods and classes in python.
Requirements and Specifications
Write a decorator named @class_method that, when used on a function defined within a class (i.e., a def statement nested immediately within a class statement), converts it into a class method, meaning two things.
The method can be called on the class as a whole, rather than on an object of that class.
Whether called on the class as a whole or an object of that class, its first parameter will be the class, rather than an object of that class. In other words, rather than having a self parameter, it has a cls parameter.
Write a class named LimitedString meeting the following requirements.
Constructing a LimitedString requires one positional argument that specifies a maximum length. This maximum length must be a non-negative integer; anything else should cause a ValueError to be raised.
A LimitedString object is a descriptor that can be used to enforce that an object attribute's value is a string, and that its length is no longer than the maximum length.
If an optional keyword argument can_delete is passed when constructing a LimitedString, it controls whether an attribute described by it can be deleted from an object — True if it can, or False if it cannot. (If can_delete, deleting the attribute causes an AttributeError to be raised.)
Source Code
PROBLEM 1
@classmethod
def foo(cls, x, y):
return cls.__name__, x+y
PROBLEM 3
class LimitedString:
def __init__(self, length, can_delete = True):
if not isinstance(length, int):
raise ValueError
if length < 0:
raise ValueError
self.length = length
self.can_delete = can_delete
self.value = None
def __repr__(self):
if self.value is None:
raise AttributeError
return self.value
def __set__(self, instance, value):
if not isinstance(value, str):
raise ValueError
if len(value) > self.length:
raise ValueError
self.value = value
def __delete__(self, instance):
if not self.can_delete:
raise AttributeError
self.value = None