logo
down
shadow

Instantiating a python class from a module by full name


Instantiating a python class from a module by full name

By : user3042302
Date : November 27 2020, 05:23 PM
around this issue I've managed to write an extension class which would provide a similar functionality to a regular python's "from X import Y". In the end I had to use the default ImportModule to import the very root of the module hierarchy and traverse down the structure to find the necessary module:
code :
private static PythonModule TraverseDown(PythonModule module, string moduleName)
{
    return (PythonModule) module.Get__dict__()[moduleName];
}

private static PythonModule TraverseToTarget(ScriptScope scope, string moduleName)
{
    // The root of the module was already imported by the engine's import module call. 
    var moduleNameParts = moduleName.Split('.').Skip(count: 1).ToList();
    var rootModule = scope.GetVariable<PythonModule>(moduleNameParts.First());
    return moduleNameParts.Skip(count: 1).Aggregate(rootModule, TraverseDown);
}

public static dynamic ImportFromModule(this ScriptEngine engine, string moduleName, string targetImport)
{
    var rootModuleScope = engine.ImportModule(moduleName);
    var targetModule = TraverseToTarget(rootModuleScope, moduleName);
    return targetModule.Get__dict__()[targetImport];
}
// Here's a sample input:
var moduleName = "sp.content.abilities.torpedo"
var className = "AbilityTorpedo"

// Here's my module loading and class instaitiation
var moduleScope = ScriptEngine.ImportFromModule(moduleName, className);
return ScriptEngine.Operations.CreateInstance(scriptClass);


Share : facebook icon twitter icon
Instantiating a ruby class that is in a Module from within C#

Instantiating a ruby class that is in a Module from within C#


By : Sean.SanzoMaldini
Date : March 29 2020, 07:55 AM
With these it helps I know this is kind of a hack/workaround, but I managed to do it this way:
Add the next code to the end of your ruby file:
code :
def hack(s)
  eval(s)
end
var engine = Ruby.CreateEngine();

var scope = engine.ExecuteFile(@"c:\code\generator\lib\generator\generator_cmd_line.rb");

var genCmdLineObj = engine.Execute(String.Format("hack('{0}::{1}')", "Generator", "CmdLine"), scope);
var cmdLineObj = engine.Operations.CreateInstance(genCmdLineObj);
var results = engine.Operations.InvokeMember(cmdLineObj, "run");
return Content(results);
How can I get a full list of class members without instantiating a class?

How can I get a full list of class members without instantiating a class?


By : user3432772
Date : March 29 2020, 07:55 AM
Any of those help Good day! , I'm not sure I know what you mean:
code :
class a(object):
    b = 'a'
    c = 'd'

print dir(a)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'b', 'c']
print [i for i in dir(a) if not i.endswith('__')]
Dynamically importing a module and instantiating a class in Python

Dynamically importing a module and instantiating a class in Python


By : user3453363
Date : March 29 2020, 07:55 AM
This might help you If everything in your module are classes that you should instanciate, try something like this :
for a in actions:
code :
try:
    module = __import__("actions.%s" % a, globals(), locals(), fromlist=["*"])
    # What goes here?
    # let's try to grab and instanciate objects
    for item_name in dir(module):
        try:
           new_action = getattr(module, item_name)()
           # here we have a new_action that is the instanciated class, do what you want with ;)
        except:
           pass

except ImportError:
    pass
VBA - Naming and Instantiating a Class Module

VBA - Naming and Instantiating a Class Module


By : Olusegun J
Date : March 29 2020, 07:55 AM
it should still fix some issue VBA is not case sensitive like C# so class1 and Class1 are the same things..
There is nothing seriously wrong (meaning: since the compiler allows that...) with using the same name for an object instance as its class except in general it would be considered a really bad programming practice to use the same name for class instance as its class.
Declaring a class in a Lua module and then instantiating it

Declaring a class in a Lua module and then instantiating it


By : Jessica Diaz
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , The self parameter is only implicit when using the OOP style.. You need to call it like this as well:
code :
local t = c:new()
--         ^
Related Posts Related Posts :
  • Passing enum type to Converter with integer value
  • Pool of objects with objects that are already on the scene in advance
  • StatusBar text fade-out when binding using Caliburn.Micro
  • Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
  • How to get record form a different table based on a value from first table with linq expression?
  • Show data in Grid from returned model
  • Using Attributes to Override Data Model Conventions
  • Basic OOP console calculator, result Error
  • Compositon and Repository pattern
  • Multiple using statements with if condition
  • How do i increase a number by 1 in every line that contain the number 1
  • Add binding to elements that are created in codebehind
  • How to add a column in an existing AspNetUsers table
  • Order a list of elements with another list of doubles
  • How to setup a NuGet package to copy content files to output build directory?
  • In SignalR Core using ChannelWriter: Do I need to call TryComplete twice if there's an exception?
  • C# GetProcessesByName: issue with colon
  • c# wpf | create complex object with user-defined name to Serialize into JSON
  • How can I get a instance of a generic list with reflection?
  • WPF XAML - Design time and visibility of textbox
  • EF Core and MySql query is too slow
  • Getting Registered App Display Name from an App Id
  • How to get all variables from a string
  • Delete entity with all childs connected
  • Azure Build agent cant´t find class library referance
  • Initialize Nested Dictionaries in c#
  • .Net Core Binding
  • Loading a pop up page in ASP.net through a js file
  • How to pass alert or notification message from controller to View?
  • C# to pause, turn on ssas server, backup cube.... how to?
  • How to execute DataTable.Select() for a column of custom class type for a particular element in that C#
  • how to connect mysql8.0 with C#
  • Passing incorrect values into MultiValueConverter by MultiBinding
  • Can i use IEnumerator as Update func?
  • How to convert API Json response to C# Array?
  • Blazor Textfield Oninput User Typing Delay
  • Performing both layout and render transform results in wrong output
  • uwp beforetextchanged cursor moving in front of text
  • How to keep duplicates from a string[] exclude words from a List and print them out
  • .Net Core Strings.Asc/Mid/Chr/Len missing even after importing Microsoft.VisualBasic
  • How to return to previous search page without being asked to Confirm Form Re-submission and keeping the results on ASP.N
  • How set a identity scaffolding item/page how initial page in asp.net MVC core?
  • LINQ isn't calling Dispose on my IEnumerator when using Union and Select, expected behavior or bug?
  • What is "ByteArray.uncompress()" in AS3 equivalent to in C#?
  • Getting a specific letter from a string variable for my simple guessing game for clues
  • Send an email with Outlook without a subject --- dialog box issue
  • passing List<MyModel> from my controller in the "WebInterfaceProject" to the processor method in "D
  • How to convert Word document created from template by OpenXML into MemoryStream?
  • How can I make a single slider that changes the color of an object?
  • Remap JSON parameter in c#
  • What is the difference between "this ref" and "ref this" when talking about C# 7.2 ref extension met
  • Convert OpenSSL encryption into native C#
  • Accessing Properties in Razor Pages
  • How to get SOAP element value
  • Projection after Group
  • C# error cannot convert sytem.text.regularexpressions.match to string
  • Issues with Save/Load System in a Text Based Adventure game made with ScriptableObjects in Unity
  • VS2019 MSBuild.exe - ASP .Net MVC project fails to publish when using PublishProfile, but works when using OutDir parame
  • Does <pages validateRequest="false" /> in Web.config still matter?
  • How to send new request to redirect URL with new access token
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org