Using latest Jython 2.6 beta-1 I derive a custom class MyGame from an imported Java class Game, then I want to override the method render() in my sub class. Within that method I want to call the render() method of the parent (Java) class.
I tried three different versions of how to call this super method, but none work.
from com.badlogic.gdx import Game
class MyGame(Game):
def render(self):
# here I want to call super's render(), which takes no arguments;
# but none of the following three options work.
Game.render() # error: expected 1 args; got 0
Game.render(self) # error: render() takes exactly 1 argument (2 given)
self.super__render() # error: render() takes exactly 1 argument (2 given)
Any ideas?
The builtin super allows you to call the parent class render method.
from com.badlogic.gdx import Game
class MyGame(Game):
def render(self):
super(Game, self).render()
Related
I am writting a custom module for Micropython called System. The System class is written in C and has the function testpass.
// System class test function
STATIC mp_obj_t system_testpass( mp_obj_t self_in, mp_obj_t thing_in )
{
// How do I get the Thing object so I can access its members?
printf("Thing: %d\r\n", thing->test );
return MP_ROM_NONE;
}
MP_DEFINE_CONST_FUN_OBJ_2(system_testpass_obj, system_testpass);
I have another class called Thing that is written in Python.
class Thing():
def __init__( self, test ):
self.test = test
How do I use the Thing class in the System 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.
In the following code;
unit module Fancy::Calculator;
what does 'unit' actually do? I know that the scope for the definition of the module becomes the file its declared in - as opposed to;
module Fancy::Calculator {
# module definition statements here
}
where the scope is obviously defined by the curlies but I can't see anything in the documentation that definitively states that that is all that it does and I'd be a little surprised if that's all that it did. Secondarily, after making such a declaration, can one declare unit class Whatever (class, module, whatever) half way down and call an end to the previous scope definition?
From a commenter (thanks Brad), it appears that is all it does. As for starting a second Module within the same file - you can't use unit module again - that produces;
===SORRY!=== Error while compiling /home/user/Fancy/Calculator.pm6
Too late for unit-scoped module definition;
Please use the block form.
...but as the message says, you can use the block form but whatever you declare is within the unit module namespace - Fancy::Calculator in this case. So these;
unit module Fancy::Calculator;
# The following available to the module user as Fancy::Calculator::Adder
class Adder {
method add { "Hi... I am a method who can add" }
}
# Starting definition of new module but its within Fancy::Calculator namespace
module Minus {
# Following available to the module user as Fancy::Calculator::Minus::Subber
class Subber {
method subtract { "Hi... I am a method who can subtract" }
}
# unless you add "is export" in which case its available by its short name
class Multiplyer is export {
method times { "Hi... I am a method who can multiply" }
}
sub divide() is export { "Hi... I am a sub who can divide" }
}
are accessed like this;
# In main
use Fancy::Calculator;
my $fca = Fancy::Calculator::Adder.new;
say $fca.add; # Hi... I am a method who can add
my $fcms = Fancy::Calculator::Minus::Subber.new;
say $fcms.subtract; # Hi... I am a method who can subtract
my $mul = Multiplyer.new;
say $mul.times; # Hi... I am a sub who can multiply
say divide(); # Hi... I am a sub who can divide
I've looked through the Jython book on Jython.org and perused the Internet for some answers but I don't see anywhere that suggests the following (of what seems to me to be strange) behavior. I'm doing this using PyDev 1.5.7 in Eclipse 3.6.1 with Jython 2.5.3.
Does a Jython class that inherits from a Java interface with setters automatically call the setVal when self.val = val is executed?
Here's the Java interface:
package com.me.mypackage
import org.python.core.PyDictionary;
public interface MyInterface {
public double getMaxBW();
public boolean setMaxBW(double bw);
}
Here's the Jython class:
from com.me.mypackage import MyInterface
class MyClass(MyInterface):
def __init__(self, maxBW):
self.maxBW = maxBW
def setMaxBW(self, maxBW):
self.maxBW = maxBW
def getMaxBW(self):
return self.maxBW
When I instantiate the class, in the __init__ function:
setMaxBW gets called when self.maxBW = maxBW is run
This function call in turn runs self.maxBW = maxBW
This code again calls setMaxBW
This function call in turn runs self.maxBW = maxBW
Repeat forever
As a result of this infinite recursion, I get a RuntimeError after the maximum recursion depth has been reached.
One thought was that this was something nifty new-style Python classes were doing (I've spent most of my Python time with old-style classes) but this problem doesn't occur with pure Jython (in Eclipse or standalone from the command line) that doesn't inherit from the Java interface. I haven't tried the interface inheritance outside of Eclipse.
And now I reiterate my initial question but in the context of my code: Is a Jython class that inherits a Java interface with setters automatically call setMaxBW when self.maxBW = maxBW is executed?
Well, I have something like this:
trait A
class Serving(a: => A)
object App extends Serving(App.Main) {
object Main extends A
}
And I get the error super constructor cannot be passed a self reference unless parameter is declared by-name. I can work around by doing
object App extends Serving(Serv.Main)
object Serv {
object Main extends A
}
but I don't want to. It adds 2 extra .classes and it strikes me as unelegant.
And using object App extends Serving(this.Main) also creates an error. The structure of A and Serving cannot really be changed, but is there any way to work around this error?
Your code compiles just fine in Scala 2.8.1, even if the parameter is not declared by-name.