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):
        self.brand=str(brand)

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

class Car{
    private String brand;
    public Car(String brand){
        this.brand=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):
        self.brand=str(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):
        self.brand=str(brand)
        self.price=int(price)
    def __str__(self):
        return "This %s car costs about $%d "%(self.name,self.price)
    
myCar=Car("Toyota",3000)
print(myCar.__dict__)

The result will be:

{'brand':'Toyota','price':3000}

This is a super useful method.

 

发表评论

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