Python magic methods

There are far more magic methods in Python than we could ever hope to cover. However, we believe that the arithmetic and boolean magic methods are fairly intuitive to use, and so don’t deserve special attention.What are magic methods? They’re everything in object-oriented Python. They’re special methods that you can define to add “magic” to your classes. They’re always surrounded by double underscores (e.g. __init__ or __lt__).

Magic Method When it gets invoked (example) Explanation
__new__(cls [,...]) instance = MyClass(arg1, arg2) __new__ is called on instance creation
__init__(self [,...]) instance = MyClass(arg1, arg2) __init__ is called on instance creation
__cmp__(self, other) self == other, self > other, etc. Called for any comparison
__pos__(self) +self Unary plus sign
__neg__(self) -self Unary minus sign
__invert__(self) ~self Bitwise inversion
__index__(self) x[self] Conversion when object is used as index
__nonzero__(self) bool(self) Boolean value of the object
__getattr__(self, name) self.name # name doesn't exist Accessing nonexistent attribute
__setattr__(self, name, val) self.name = val Assigning to an attribute
__delattr__(self, name) del self.name Deleting an attribute
__getattribute__(self, name) self.name Accessing any attribute
__getitem__(self, key) self[key] Accessing an item using an index
__setitem__(self, key, val) self[key] = val Assigning to an item using an index
__delitem__(self, key) del self[key] Deleting an item using an index
__iter__(self) for x in self Iteration
__contains__(self, value) value in self, value not in self Membership tests using in
__call__(self [,...]) self(args) “Calling” an instance
__enter__(self) with self as x: with statement context managers
__exit__(self, exc, val, trace) with self as x: with statement context managers
__getstate__(self) pickle.dump(pkl_file, self) Pickling
__setstate__(self) data = pickle.load(pkl_file) Pickling

35 thoughts on “Python magic methods”

  1. I’m not certain where you’re getting your information, however good topic.
    I must spend a while learning more or understanding more.
    Thanks for magnificent info I was searching for this info for my mission.

  2. Pingback: Homepage
  3. Your site is extremely cool. It unveils how
    nicely you understand this subject. Bookmarked this web site, will come back for a
    lot more articles. You, amigo, ROCK! I found simply the information I already
    searched in all places and simply couldn’t come across.

    What an ideal website.

  4. You actually make it seem really easy along with your presentation however I to find this matter to be really one
    thing that I believe I’d never understand. It seems too complex and extremely extensive for
    me. I’m having a look forward in your next submit, I’ll
    attempt to get the hang of it!

  5. Hello! I realize this iss somewhat off-topic but I needed to
    ask. Does managing a well-established website such as yours take
    a massive amount work? I am completesly new to writing a blog however I ddo write
    in my journal everyday. I’d like to start a blog sso I can sharee my personal experience andd viewws online.
    Please lett me know if you have any recommendations orr tips forr new aspirinng bloggers.
    Appreciate it!

    Look at my web blog … droping basemode

  6. Hello very nice site!! Guy .. Excellent .. Amazing ..
    I’ll bookmark your website and take the feeds additionally?
    I am happy to find a lot of helpful info here in the post,
    we’d like develop extra strategies on this regard, thank you for sharing.
    . . . . .

  7. I’m really enjoying the design and layout of your blog. It’s a very easy on the
    eyes which makes it much more pleasant for me
    to come here and visit more often. Did you hire out a developer to create your theme?
    Superb work!

  8. Having read this I thought it was rather enlightening.
    I appreciate you taking the time and effort to put this article together.
    I once again find myself spending a significant amount of time both reading and
    commenting. But so what, it was still worth it!

  9. I do consider all of the concepts you’ve introduced for your post.
    They are really convincing and will definitely
    work. Nonetheless, the posts are very quick for newbies.
    May you please lengthen them a bit from subsequent time?
    Thanks for the post.

  10. My spouse and I absolutely love your blog
    and find a lot of your post’s to be exactly I’m looking for.
    Does one offer guest writers to write content for you?

    I wouldn’t mind writing a post or elaborating on a few of
    the subjects you write related to here. Again, awesome site!

  11. Hey There. I discovered your weblog the usage of msn. This is a really well
    written article. I’ll make sure to bookmark it and return to read extra of your helpful info.
    Thank you for the post. I will certainly comeback.

  12. I’m truly enjoying the design and layout of your site.
    It’s a very easy on the eyes which makes it much more enjoyable for me
    to come here and visit more often. Did you hire out
    a developer to create your theme? Superb work!

  13. Hey there I am so happy I found your web site, I really found you by accident, while I was browsing
    on Google for something else, Anyhow I am here now and would just like to say thank you for a marvelous post and a
    all round interesting blog (I also love the theme/design), I don’t
    have time to go through it all at the moment but I have book-marked it
    and also added your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep
    up the great job.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>