Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python class definition based on a condition

Tags:

python

class

I found a similar class definition as below in a Python code base. It seems there is no similar examples in the official documents. Very hard to find similar thing by Google and searching in the forum. May anyone help me to understand the principle in Python behind this?

class a: pass
class b: pass
condition = True
class c(a if condition == True else b): pass
like image 287
shinji Avatar asked Jun 24 '13 13:06

shinji


People also ask

Can I define a class in a function Python?

We must explicitly tell Python that it is a class method using the @classmethod decorator or classmethod() function. Class methods are defined inside a class, and it is pretty similar to defining a regular function. Like, inside an instance method, we use the self keyword to access or modify the instance variables.

What are dynamic classes in Python?

Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.

Is def the same as class in Python?

class is used to define a class (a template from which you can instantiate objects). def is used to define a function or a method. A method is like a function that belongs to a class.

How do you check if an object is a class Python?

Solution Overview. In Python, the built-in functions type() and isinstance() help you determine the type of an object. type(object) – Returns a string representation of the object's type. isinstance(object, class) – Returns a Boolean True if the object is an instance of the class, and False otherwise.


1 Answers

a if condition == True else b is a ternary expression.

It means use a as base class if condition equals True else use b.

As condition == True is True so it uses a:

>>> class c(a if condition == True else b): pass
>>> c.__bases__
(<class __main__.a at 0xb615444c>,)

Examples:

>>> print 'foo' if 0>1 else 'bar'
bar
>>> print 'foo' if 1>0 else 'bar'
foo

From the docs:

The expression x if C else y first evaluates the condition, C (not x); if C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

like image 111
Ashwini Chaudhary Avatar answered Sep 23 '22 14:09

Ashwini Chaudhary