PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

[FIXED] How {condition 1: x(), condition 2: y()}.get(True, None) actually run in python?

 July 08, 2022     class, dictionary, get, if-statement, python     No comments   

Issue

I recently learned about a way to write if-elif-else. For example:

a = 10
x = {a < 1: 100, a > 1: 200}.get(True, None)

is equal to:

a = 10
if a < 1:
    x = 100
elif a > 1:
    x = 200
else:
    x = None

They will get the same result x = 200

This new way is more elegant so I use it to replace my following if-elif-else code:

i = 10
j = 0
class A:
    a = 1
class B:
    a = 2
if i:
    x = A()
elif j:
    x = B()
else:
    x = None

to

i = 10
j = 0
class A:
    a = 1
class B:
    a = 2
x = {i: A(), j: B()}.get(True, None)

However, it didn't run as I wished:

>>> x.a
None

In my opinion, the output of x.a should be 1 because i > 0.

How to explain this?


Solution

(Not a direct answer to your question)

I recently learned about a way to write if-elif-else.

Rather than:

a = 10
x = {a < 1: 100, a > 1: 200}.get(True, None)

Prefer this:

a = 10
x = 100 if a < 1 else 200 if a > 1 else None

Which is really more comprehensive, isn't it?



Answered By - Corralien
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing