>class DateTime(datetime.datetime):
>  def __init__(self, year, month, day, *args):
>    super().__init__()
>    if self.year >= 1000:
>      self.year = self.year % 1000

I have no idea how you could use the sample you have given (or why) but, this 
was actually a fun exercise that forced me to learn more about immutable types 
(which makes sense because a date should never really be modifiable if you 
think about it). Instead of overriding the __init__ you need to override the 
__new__ method. Try the following

>>> class DateTime(datetime.datetime):
...     def __new__(self, year, month, day, *args):
...         if year >= 1000:
...             year = year % 1000
...         return super( DateTime, self ).__new__(self, year, month, day, 
*args )
...     
>>> DateTime( 2011, 1, 1 )
DateTime(11, 1, 1, 0, 0)

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

From: tutor-bounces+ramit.prasad=jpmorgan....@python.org 
[mailto:tutor-bounces+ramit.prasad=jpmorgan....@python.org] On Behalf Of rail 
shafigulin
Sent: Friday, December 09, 2011 4:15 PM
To: tutor@python.org
Subject: Re: [Tutor] attribute overwrite


On Fri, Dec 9, 2011 at 4:43 PM, rail shafigulin <rail.shafigu...@gmail.com> 
wrote:
i need to overwrite and attribute from the inherited class. i also need to run 
the constructor of the super class. here is the code

import datetime

class DateTime(datetime.datetime):
  def __init__(self, year, month, day, *args):
    super().__init__(year, month, day, *args)
    if self.year >= 1000:
      self.year = self.year % 1000

i'm getting the following error:
AttributeError: attribute 'year' of datetime.datetime objects are not writable.

some of you might suggest to change

self.year = self.year % 1000
to
self.yr = self.year % 1000

but i'd need to keep the name the same.

any help is appreciated.
my apologies, but there is a minor mistake in the code:

import datetime

class DateTime(datetime.datetime):
  def __init__(self, year, month, day, *args):
    super().__init__()
    if self.year >= 1000:
      self.year = self.year % 1000

def main():
  mytme = DateTime.now()

if __name__ == '__main__'
  main()
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to