Magic Methods in Python

This first post of programming is about Python’s Magic Method

Magic Method is not marked as an essential point in the book Python Crash Course, which actually is. To distinguish it from other ordinary methods, magic methods start with two underscores.

Magic Methods are mainly used in a class. The magic methods I use frequently(and recently) are those below:

def __init__(self): It is just like the Constructor in Java,the use of which is to initialize the attribute of the class.

Keep in mind that there is no this keyword in Python.Instead of this, Python use self keyword.You cannot claim an attribute outside like Java do. Claim it in the method.

Here’s an example:

class Car():
    def __init__(self,brand):

Here’s the Java’s way of doing this:

class Car{
    private String brand;
    public Car(String brand){


def __str__(self):The method is just like the toString() method in Java,enabling you to print the object in your customized way.You should override it when you need it.

Still taking the class car as example:

class Car():
    def __init__(self,brand):
    def __str__(self):
        return "The brand of the car is %s."%self.brand

And it’s rather obvious when you run the file and make the parameter brand to Toyota,you get the result The brand of the car is Toyota.


Don’t miss this one:__dict__

The method is not put in the class. This function returns a dictionary of a certain entity (or instance in Java terms).

class Car():
    def __init__(self,brand,price):
    def __str__(self):
        return "This %s car costs about $%d "%(,self.price)

The result will be:


This is a super useful method.



电子邮件地址不会被公开。 必填项已用*标注