Sectie 2. Hoofdstuk 5
single
Challenge: Reimplementing property
Veeg om het menu te tonen
You are going to build a simplified version of Python's built-in property from scratch using the descriptor protocol. This will cement your understanding of how property works under the hood.
Your SimpleProperty descriptor must support a getter, an optional setter, and an optional deleter – matching the interface of the built-in property.
Taak
Veeg om te beginnen met coderen
- Implement a class
SimplePropertywith:__init__(self, fget=None, fset=None, fdel=None)that stores all three functions;__get__(self, obj, objtype=None)that returnsselfwhenobj is None, raisesAttributeErroriffgetisNone, otherwise calls and returnsfget(obj);__set__(self, obj, value)that raisesAttributeErroriffsetisNone, otherwise callsfset(obj, value);__delete__(self, obj)that raisesAttributeErroriffdelisNone, otherwise callsfdel(obj);- a
setter(self, fset)method that returns a newSimplePropertywith the samefgetandfdelbut the newfset; - a
deleter(self, fdel)method that returns a newSimplePropertywith the samefgetandfsetbut the newfdel.
- Apply
SimplePropertyto thePortfolioclass below:- decorate
valuewith@SimplePropertyas the getter; - use
@value.setterto add a setter that stores the value inself._valueif it is non-negative, otherwise raisesValueError; - use
@value.deleterto add a deleter that setsself._valueto0.0.
- decorate
- Create an instance called
portfoliowithportfolio_id="PF-001"andvalue=50000.0. - Store
portfolio.valuein a variable calledinitial_value. - Set
portfolio.valueto75000.0, then store the new value inupdated_value. - Print
initial_valueandupdated_value.
class Portfolio:
def __init__(self, portfolio_id, value):
self.portfolio_id = portfolio_id
self._value = value
Oplossing
Was alles duidelijk?
Bedankt voor je feedback!
Sectie 2. Hoofdstuk 5
single
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.