here is a simplified implementation of the visitor pattern in C++. Ist it possible to implement something like this in Python?
I need it, because I will pass Objects from C++ code to a function in Python. My idea was to implement a visitor in Python to find out the type of the Object.
My C++ code:
#include <iostream>
#include <string>
class t_element_base
{
public:
virtual void accept( class t_visitor &v ) = 0;
};
class t_element_deriv_one: public t_element_base
{
public:
void accept( t_visitor &v );
std::string t_element_deriv_one_text()
{
return "t_element_deriv_one";
}
};
class t_element_deriv_two: public t_element_base
{
public:
void accept( t_visitor &v );
std::string t_element_deriv_two_text()
{
return "t_element_deriv_one";
}
};
class t_visitor
{
public:
void visit( t_element_deriv_one& e ){ std::cout << e.t_element_deriv_one_text() << std::endl; }
void visit( t_element_deriv_two& e ){ std::cout << e.t_element_deriv_two_text() << std::endl; }
};
void t_element_deriv_one::accept( t_visitor &v )
{
v.visit( *this );
}
void t_element_deriv_two::accept( t_visitor &v )
{
v.visit( *this );
}
int
main
(
void
)
{
t_element_base* list[] =
{
new t_element_deriv_one(), new t_element_deriv_two()
};
t_visitor visitor;
for( int i = 0; i < 2; i++ )
list[ i ]->accept( visitor );
}
instance
call does not exists. You should useisinstance
– Duelist