How do I check if a class is defined?
How about const_defined?
?
Remember in Rails, there is auto-loading in development mode, so it can be tricky when you are testing it out:
>> Object.const_defined?('Account')
=> false
>> Account
=> Account(id: integer, username: string, google_api_key: string, created_at: datetime, updated_at: datetime, is_active: boolean, randomize_search_results: boolean, contact_url: string, hide_featured_results: boolean, paginate_search_results: boolean)
>> Object.const_defined?('Account')
=> true
How to check if a class is declared in C++?
You can, and with no macros required. First an observation, you can "forward" declare a class even after its full definition is available. I.e. this is valid:
class foo{};
class foo;
Now, with the help of a homebrew void_t
implementation and an is_complete
type utility, you can do something like this:
#include <type_traits>
template<typename... Ts> struct make_void { typedef void type;};
template<typename... Ts> using void_t = typename make_void<Ts...>::type;
template <typename T, typename Enabler = void>
struct is_complete : std::false_type {};
template <typename T>
struct is_complete<T, ::void_t<decltype(sizeof(T) != 0)>> : std::true_type {};
class A;
class B;
class C : public std::conditional<is_complete<A>::value, A, B>::type {
};
Depending on whether or not the full definition of A
is present, C
will inherit from A
or B
publicly. See a live example.
But I caution, this needs to be handled with care or you are very likely to have an ODR-violation in your program.
Python - check for class existance
Your situation is not entirely clear, so I'm just going to answer the question "Is there a way to check if a class has been defined/exists?"
Yes, there are ways to check if a class has been defined in the current scope. I'll go through a few.
1. It's Better to Ask Forgiveness Than Permission
Just try to use it!
try:
var = MyClass()
except NameError:
# name 'MyClass' is not defined
...
This is probably the most Pythonic method (aside from just being sure you have the class imported/defined).
2. Look Through Current Scope
Everything in the current scope is given by dir()
. Of course, this won't handle things that are imported! (Unless they are imported directly.)
if not 'MyClass' in dir():
# your class is not defined in the current scope
...
3. Inspect a Module's Contents
Perhaps you want to see if the class is defined within a specific module, my_module
. So:
import my_module
import inspect
if not 'MyClass' in inspect.getmembers(my_module):
# 'MyClass' does not exist in 'my_module'
...
Now, it's worth pointing out that if at any point you are using these sorts of things in production code, you're probably writing your code poorly. You should always know which classes are in scope at any given point. After all, that's why we have import statements and definitions. I'd recommend you clean up your question with more example code to receive better responses.
Check if an element contains a class in JavaScript?
Use element.classList
.contains
method:
element.classList.contains(class);
This works on all current browsers and there are polyfills to support older browsers too.
Alternatively, if you work with older browsers and don't want to use polyfills to fix them, using indexOf
is correct, but you have to tweak it a little:
function hasClass(element, className) {
return (' ' + element.className + ' ').indexOf(' ' + className+ ' ') > -1;
}
Otherwise you will also get true
if the class you are looking for is part of another class name.
DEMO
jQuery uses a similar (if not the same) method.
Applied to the example:
As this does not work together with the switch statement, you could achieve the same effect with this code:
var test = document.getElementById("test"),
classes = ['class1', 'class2', 'class3', 'class4'];
test.innerHTML = "";
for(var i = 0, j = classes.length; i < j; i++) {
if(hasClass(test, classes[i])) {
test.innerHTML = "I have " + classes[i];
break;
}
}
It's also less redundant ;)
How to check if a class in javascript exists
if (typeof class_a === 'function')
How to check if a python class or object is user defined (not a builtin)?
Try checking if the types module is builtin, usually works for me.
For example:
a = 1.2
type(a).__module__ == "__builtin__"
checking if a method is defined on the class
Use this:
C.instance_methods(false).include?(:a)
C.instance_methods(false).include?(:b)
C.instance_methods(false).include?(:c)
The method instance_methods
return an Array of methods that an instance of this class would have. Passing false
as first parameter returns only methods of this class, not methods of super classes.
So C.instance_methods(false)
returns the list of methods defined by C
.
Then you just have to check if that method is in the returned Array (this is what the include?
calls do).
See docs
Related Topics
Undefined Instance Method "Respond_To" in Rails 5 API Controller
(Ruby,Rails) Context of Self in Modules and Libraries...
Extracting the Last N Characters from a Ruby String
Ruby/Rails - .Each Iterator Is Printing Entire Array at the End of the Loop
Rails 3:How to Generate Models for Existing Database Tables
Rvm Ruby Installation Errors - MAC
What Is the "Equals Greater Than" Operator => in Ruby
Ruby Bundler Multiple Sources in Gemfile
Rails How to Get Latitude and Longitude from String Address and Put It on Google Map
Why Is Ruby Unable to Verify an Ssl Certificate
How to Specify a Required Switch (Not Argument) with Ruby Optionparser
How Mix in Routes in Sinatra for a Better Structure
Is There a Rails Console Command (Rails 3+) to Reload Changed Code
How to Use Watir::Waiter::Wait_Until to Force Chrome to Wait
Ruby Dynamic Classes. How to Fix "Warning: Class Variable Access from Toplevel"