typeError 'str' is not callable. invoke a class function using dictionary value - typeerror

#Class and function
class cf:
def duplicate(**kwargs)
....
return df[df[field].isnull()
#There is a dictionary
r={'field':'con','function':'cf.duplicate'}
#Trying to call function looping above dictionary r
for a in r:
a['function'] a['field'] #this line is showing error as str object is not callable...and as checked a['function'] is string.
need to call a class method duplicate and give output and fetching the variable from dict

Related

AttributeError: 'NoneType' object has no attribute 'value'

I'm currently working on a problem regarding Binary Search Trees. My problem is that I get the error "AttributeError: 'NoneType' object has no attribute 'value'" and I don't see what I can do about it. This code is in my BST class.
def _insert(self, data):
if self.root.value == data:
return False
I have a Node class and a BinarySearchTree class.
class _Node:
def __init__(self, value):
self.right_child = None
self.left_child = None
self.value = value
class BST:
def __init__(self):
self.root = None
I imagine it has something to do with the fact that self.root is set to None in my init() function. How can I fix this problem?
self.root is None so when you check self.root.value, the root has no such element.
Instead of initializing self.root=None, initialize self.root=Node(None)
Also while inserting, if you are planning to insert to root, then check if the root.value is None, if yes, insert else the rest of your logic

Instantiate only unique objects of a class

I'm trying to create a class that only creates an instance if the arguments passed in during instantiation are a unique combination. If the combination of arguments have previously been passed in, then return the instance that has already been previously created.
I'd like for this class to be inherited by other classes so they inherit the same behavior. This is my first attempt at a solution,
The base/parent class to be inherited:
class RegistryType(type):
def __init__(cls, name, bases, namespace, *args):
cls.instantiated_objects = {}
class AdwordsObject(object, metaclass=RegistryType):
api = AdWordsAPI()
def __new__(cls, *args):
object_name = '-'.join(args)
if object_name in cls.instantiated_objects:
return cls.instantiated_objects[object_name]
else:
obj = super(AdwordsObject, cls).__new__(cls)
cls.instantiated_objects[object_name] = obj
# cls.newt_connection.commit()
return obj
And this is how it's being used in the child class:
class ProductAdGroup(AdwordsObject):
# init method only called if object being instantiated hasn't already been instantiated
def __init__(self, product_name, keyword_group):
self.name = '-'.join([product_name, keyword_group])
#classmethod
def from_string(cls, name: str):
arguments = name.split('-')
assert len(arguments) == 2, 'Incorrect ad group name convention. ' \
'Use: Product-KeywordGroup'
ad_group = cls(*arguments)
return ad_group
I've ran the program with this setup but it seems like a new dict is being created every time ProductAdGroup() is being created so the memory is exploding... even though the program returns the instance that had already been previously instantiated.
Is there anyway to fix this?
Thanks!!!
Your code seems to be right - the only thing incorrect above is that your __init__ method will always be called when instantiating a new class, regardless of a previous instance being returned by __new__ or not.
So, if you create extra objects in your __init__ method, that may be the cause of your memory leak - however, if you bind these new objects to the instane (self), they shuld just override a previously created object in the same place - which would them be freed. . In the code posted here, that happens with self.name- it may be that your real __init__ does more things, and associate new objects to other places than the instance (like, apending them to a list). If your __init__ methods are just as shown the cause for your memory growing is not evident in the code you supply.
As an extra advice, but not related to the problem you relate, I add that you don't need a metaclass for this at all.
Just check for the existence of an cls.instantiated_objects dict in the __new__ method itself. Not writting an unneeded metaclass will simplify your codebase, avoid metaclass conflicts if your class hierarchy evolves, and may even do away with your problem if there is more code on your metaclass than you are showing here.
The base class __new__ method can be rewritten something like this:
class AdwordsObject(object):
def __new__(cls, *args):
if not cls.__dict__.get("instantiated_objects"):
cls.instantiated_objects = {}
name = '-'.join(args)
if name in cls.instantiated_objects:
return cls.instantiated_objects[name]
instance = super().__new__(cls)
cls.instantiated_objects[name] = instance
return instance
And there is no more need for a custom metaclass.

A constructor with only 1 argument in Perl 6

I want to override new so that my class can be created only by passing one argument to the constructor, no more and no fewer.
class MyClass {
has $.var1;
method new($var1) {
return MyClass.new(var1 => $var1);
}
}
my $my_class1 = MyClass.new(33);
say $my_class1.var1;
The error is:
Too few positionals passed; expected 2 arguments but got 1
in method new at test1.pl6:28
in method new at test1.pl6:28
in block <unit> at test1.pl6:33
What's up with it?
Custom constructors need to call bless, ie
class MyClass {
has $.var1;
method new($var1) {
return self.bless(var1 => $var1);
}
}
There are a few things that can be improved, eg
one could add an explicit invocant parameter and use :U to make .new() fail when called on instance objects
the explicit return is superfluous - the last expression within the method will be returned anyway, and currently, it actually hurts performance
there's syntactic sugar for passing a named argument held in a variable of the same name
Putting it all together, we end up with
class MyClass {
has $.var1;
method new(MyClass:U: $var1) {
self.bless(:$var1);
}
}
As to where your error comes from:
Your method new is declared to take a positional argument (giving a total count of 2 expected arguments due to the implicit invocant), but the call MyClass.new(var1 => $var1) only passed a named one. Note that said method is the only .new() present in your class, so if the call had actually worked, you would have ended up with infinite recursion!

What does variable-initialization line do in VB.Net?

Can someone please tell what the following line of VB.Net is initializing:
Dim x As SomeType() = New SomeType(0) {}
What holds x variable? Is it an array? How can it be translated to C# for example?
I guess SomeType is probably an anonymous type, but still have no clue...
The line:
Dim x As SomeType() = New SomeType(0) {}
declares an array of SomeType objects, which can hold one instance of SomeType.
When declaring an array of objects the value that is passed into the constructor is the max index of the array. So this declaration is basically declaring an array with a length of 1. The {} portion of the line is where you could define the values that should be stored in the array. If you were to change SomeType to integer you could instantiate and fill your array like:
Dim intArray as Integer() = New Integer(0) {7}
and that would give the first instance stored in the intArray variable a value of 7.
SomeType is not an anonymous type. SomeType would be a class that would have to be defined somewhere in your app.
In C# I think the sytax would look like:
SomeType[] x = new SomeType[0];
I'm not exactly sure how you would accomplish the {} portion of the VB.NET line in C#.
It's simply declaring and initializing an array of a given type. In C# I think it would be, quite similarly:
SomeType[] x = new SomeType[0] { };
Is it an array?
Yes. VB uses () for arrays instead of C#'s [].
I guess SomeType is probably an anonymous type
No, it's a defined static type like any other.

How to get the handle of a method in an Object (class inst) within MATLAB

I'm trying to grab a method handle from within an object in MATLAB, yet something in the sort of str2func('obj.MethodName') is not working
The answer is to get a function handle as #Pablo has shown.
Note that your class should be derived from the handle class for this to work correctly (so that the object is passed by reference).
Consider the following example:
Hello.m
classdef hello < handle
properties
name = '';
end
methods
function this = hello()
this.name = 'world';
end
function say(this)
fprintf('Hello %s!\n', this.name);
end
end
end
Now we get a handle to the member function, and use it:
obj = hello(); %# create object
f = #obj.say; %# get handle to function
obj.name = 'there'; %# change object state
obj.say()
f()
The output:
Hello there!
Hello there!
However if we define it as a Value Class instead (change first line to classdef hello), the output would be different:
Hello there!
Hello world!
One could also write
fstr = 'say';
obj.(fstr)();
This has the advantage that it does not require a handle class to work if the object (obj) is modified.
Use #. The following code works for me:
f = #obj.MethodName
No other answer mimics str2func('obj.MethodName'). Actually, this one doesn't either, not exactly. But you can define an auxillary function like so:
function handle = method_handle(obj, mstr)
handle = #(varargin) obj.(mstr)(varargin{:});
end
Then method_handle(obj, 'MethodName') returns a handle to obj.MethodName. Unfortunately, you cannot pass the variable name of obj as a string - eval("obj") will be undefined in the function's scope.