Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

isinstance and issubclass

>>> class P(object):  # parent class
	pass

>>> class K(P):       # subclass
	pass

>>> k = K()           # instace
>>> isinstance(k, K)
True
>>> isinstance(k, P)
True
>>> isinstance(K, P)  # K is a class
False

>>> issubclass(K, P)
True
>>> issubclass(k, P)  # k is not a class

TypeError: issubclass() arg 1 must be a class

>>> isinstance(K, type)  # a class is an instace of type
True
>>> isinstance(k, type)  # not a class
False

Example of Detecting Subclasses

class A
def A.inherited(clazz)
puts "Hey, #{clazz} is subclassing me"
end
end

class B < A; end


Produces:

$ ruby x.rb
Hey, B is subclassing me
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS