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
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.
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.
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.
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.
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
(notx
); ifC
is true,x
is evaluated and its value is returned; otherwise,y
is evaluated and its value is returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With