为什么EAFP被认为是pythonic?

时间:2017-05-21 12:33:45

标签: python

考虑以下示例,

myList = [1, 2, 3, 4, 5, 6]

要打印最后一个索引,

# Non - pythonic
if len(myList) >= 6:
   print(myList[5])
else:
   print('Index does not exist')

# Pythonic
try:
   print(myList[5])
except:
   print('Index does not exist')

在获得许可的情况下,请求宽恕的偏好背后的理念是什么?

1 个答案:

答案 0 :(得分:0)

我不能说是否有某些东西是Pythonic,但我可以说出为什么它会导致更简洁的代码。一般来说,你做了很多事情,而不只是看一个索引。那么考虑当我在字典中查看几个属性时会发生什么:

import java.awt.*;


import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;


 public class Snake1 extends  JPanel implements ActionListener, KeyListener{


 JFrame frame;



JPanel Panel;

Timer timer = new Timer(20, this);

ArrayList<Point> snakeParts = new ArrayList<Point>();

int UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3;

int ticks = 0, direction = DOWN, score, tailLength = 10, time;

Point head, cherry;

Random random;

boolean over = false, paused;



//konstruktor
public Snake1(){




    //skapa objekt
    frame = new JFrame("Snake");
    Panel = new JPanel();
    head = new Point(0, -1);
    random = new Random();
    cherry = new Point(random.nextInt(79), random.nextInt(66));
    //sätta egenskaper
    over = false;
    paused = false;
    time = 0;
    score = 0;
    tailLength = 14;
    ticks = 0;
    direction = DOWN;
    timer.start();
    //sätt layout

    /*snakeParts.clear();*/


    //lägg på lysnnare
    frame.addKeyListener(this);
    //bygga fönsteret
    this.add(Panel);
    frame.add(this);
    //obligatoriska delar

    frame.setVisible(true);
    frame.setSize(805, 700);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
public void paintComponent(Graphics g){
    super.paintComponent(g);



    g.setColor(Color.white); 

    g.fillRect(0, 0, 800, 700);

    g.setColor(Color.black);

    for (Point point : snakeParts){
        g.fillRect(point.x * 10, point.y * 10, 10, 10);
    }

    g.fillRect(head.x * 10, head.y * 10, 10, 10);

    g.setColor(Color.RED);

    g.fillRect(cherry.x * 10, cherry.y * 10, 10, 10);

    String string = "Score: " + score + ", Length: " +tailLength + ", Time: " + time / 40;

    g.setColor(Color.black);

    g.drawString(string, (int) (getWidth() / 2 - string.length() * 2.5), 10);

    string = "Game Over!";

    if (over)
    {
        g.drawString(string, (int) (380),300);
    }

    string = "Paused!";

    if (paused && !over)
    {
        g.drawString(string, (int) (380),300);
    }
}





public static void main(String[] e) {
    new Snake1();
}

public void actionPerformed(ActionEvent arg0)
{
    Panel.repaint();
    ticks++;

    if (ticks % 1 == 0 && head != null && !over && !paused)
    {
        time++;

        snakeParts.add(new Point(head.x, head.y));

        if (direction == UP)
        {
            if (head.y - 1 >= 0 && noTailAt(head.x, head.y - 1))
            {
                head = new Point(head.x, head.y - 1);
            }
            else
            {
                over = true;

            }
        }

        if (direction == DOWN)
        {
            if (head.y + 1 < 67 && noTailAt(head.x, head.y + 1))
            {
                head = new Point(head.x, head.y + 1);
            }
            else
            {
                over = true;
            }
        }

        if (direction == LEFT)
        {
            if (head.x - 1 >= 0 && noTailAt(head.x - 1, head.y))
            {
                head = new Point(head.x - 1, head.y);
            }
            else
            {
                over = true;
            }
        }

        if (direction == RIGHT)
        {
            if (head.x + 1 < 80 && noTailAt(head.x + 1, head.y))
            {
                head = new Point(head.x + 1, head.y);
            }
            else
            {
                over = true;
            }
        }

        if (snakeParts.size() > tailLength)
        {
            snakeParts.remove(0);

        }

        if (cherry != null)
        {
            if (head.equals(cherry))
            {
                score += 10;
                tailLength+=7;
                cherry.setLocation(random.nextInt(80), random.nextInt(26));
            }
        }
    }
}

public boolean noTailAt(int x, int y)
{
    for (Point point : snakeParts)
    {
        if (point.equals(new Point(x, y)))
        {
            return false;
        }
    }
    return true;
}
@Override
public void keyPressed(KeyEvent e) {
    int i = e.getKeyCode();

    if ((i == KeyEvent.VK_A || i == KeyEvent.VK_LEFT) && direction != RIGHT)
    {
        direction = LEFT;
    }

    if ((i == KeyEvent.VK_D || i == KeyEvent.VK_RIGHT) && direction != LEFT)
    {
        direction = RIGHT;
    }

    if ((i == KeyEvent.VK_W || i == KeyEvent.VK_UP) && direction != DOWN)
    {
        direction = UP;
    }

    if ((i == KeyEvent.VK_S || i == KeyEvent.VK_DOWN) && direction != UP)
    {
        direction = DOWN;
    }

    if (i == KeyEvent.VK_SPACE)
    {
        if (over)
        {

        }
        else
        {
            paused = !paused;
        }
    }
}




@Override
public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub

}
@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}
}

这些分配中的每一个都必须是if语句而不使用异常处理。也就是说,您可以在try块中执行的操作越多,整体代码处理错误所需的百分比就越少。