I have a class:
class TestClass def method1 end def method2 end def method3 end end
How can I get a list of my methods in this class (method1
, method2
, method3
)?
Method 1 – Using the dir() function to list methods in a class. To list the methods for this class, one approach is to use the dir() function in Python. The dir() function will return all functions and properties of the class. Let's see what happens if we try it for MyClass .
Print an Object in Python Using the __str__() Method Now, let's define the __str__() method of our example class ClassA and then try to print the object of the classA using the print() function. The print() function should return the output of the __str__() method.
There are two standard approaches for defining class method in Ruby. The first one is the “def self. method” (let's call it Style #1), and the second one is the “class << self” (let's call it Style #2). Both of them have pros and cons.
You actually want TestClass.instance_methods
, unless you're interested in what TestClass
itself can do.
class TestClass def method1 end def method2 end def method3 end end TestClass.methods.grep(/method1/) # => [] TestClass.instance_methods.grep(/method1/) # => ["method1"] TestClass.methods.grep(/new/) # => ["new"]
Or you can call methods
(not instance_methods
) on the object:
test_object = TestClass.new test_object.methods.grep(/method1/) # => ["method1"]
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