Hi I am looking for method to define what the parent of a native widget is in gtk3
for example in Python:
def herit_of( widget):
and for Gtk.image
print herit_of(Gtk.image)
>>> Gtk.Misc
Here's a link.
If one want to know what are the ancestors of a class, there is the __mro__ tuple.
Example:
class Foo(object):
pass
class Bar(Foo):
pass
print(Foo.__mro__)
bar = Bar()
print(bar.__class__.__mro__)
It's ok for me.
the test code follow for how to
from gi.repository import Gtk
class Bar(Gtk.Window):
pass
bar = Bar()
info= bar.__class__.__mro__
for element in info:
print element
the result is
class '__main__.Bar'
class 'gi.overrides.Gtk.Window'
class 'gi.repository.Gtk.Window'
class 'gi.repository.Gtk.Bin'
class 'gi.overrides.Gtk.Container'
class 'gi.repository.Gtk.Container'
class 'gi.overrides.Gtk.Widget'
class 'gi.repository.Gtk.Widget'
class 'gi.repository.GObject.InitiallyUnowned'
class 'gi.overrides.GObject.Object'
class 'gi.repository.GObject.Object'
type 'gi._gobject.GObject'
class 'gi.repository.Atk.ImplementorIface'
class 'gi.repository.Gtk.Buildable'
type 'gobject.GInterface'
type 'object'
with this data I should build a tree of dependance
very cool
Related
I have two classes that inherit from the same base class, and they have some common methods (in fact, properties). I will need to do this:
input: an int and an object from either class;
output: the result of one of the methods (determined by the int) of the corresponding class.
I think I can use a dictionary to do this, as the following code:
class ChangeInt(object):
def bar(self, i):
print(i)
class PlusOne(ChangeInt):
def bar(self, i):
print(i+1)
class PlusTwo(ChangeInt):
def bar(self, i):
print(i+2)
methods_dict = {0:ChangeInt.bar}
print(methods_dict[0](PlusOne(), 0))
print(methods_dict[0](PlusTwo(), 0))
I expect the output to be 1,2, but I actually get this:
0
None
0
None
I would like to know how these results are generated and what should I do to fix it up. Thanks in advance.
I totally mess up the format in the comment, so I'll paste it here.
thanks to Ryan Haining in Dynamic Method Call In Python 2.7 using strings of method names, I've found another way to do this:
class ChangeInt(object):
def bar(self, i):
print(i)
class PlusOne(ChangeInt):
def bar(self, i):
print(i+1)
class PlusTwo(ChangeInt):
def bar(self, i):
print(i+2)
methods_dict = {0:'bar'}
getattr(PlusOne(), methods_dict[0])(0)
getattr(PlusTwo(), methods_dict[0])(0)
This may not be the best way to do it, but it produces the expected result:
class ChangeInt(object):
def bar(self, i):
if not ('ChangeInt' in str(self.__class__)):
self.bar(i)
else:
print(i)
class PlusOne(ChangeInt):
def bar(self, i):
print(i+1)
class PlusTwo(ChangeInt):
def bar(self, i):
print(i+2)
methods_dict = {0:ChangeInt.bar}
methods_dict[0](ChangeInt(), 0)
methods_dict[0](PlusOne(), 0)
methods_dict[0](PlusTwo(), 0)
and prints:
0
1
2
The bar() function in the base class calls the method associated with given self instance or the base class implementation if it's an instance of base class itself (just print(i)). This is important, without it the code will be calling self.bar(i) infinitely if you invoke it on the base class (i.e. until it reaches max allowable recursion call number).
The check if not ('ChangeInt' in str(self.__class__)): is necessary since issubclass will return True for the parent class too,
issubclass(class, classinfo)
Return true if class is a subclass
(direct, indirect or virtual) of classinfo. A class is considered a
subclass of itself. classinfo may be a tuple of class objects, in
which case every entry in classinfo will be checked. In any other
case, a TypeError exception is raised.
And the point is to distinguish between the base/parent class and any subclasses.
Finally, since your function calls don't return anything explicitly, they actually return None. That None is what you are printing when enclosing the calls in an additional print,
print(methods_dict[0](PlusOne(), 0))
I removed the extra print so you only print the (assuming) intended content.
I have two classes defined like so in my models.py file:
class Branch_Circle(models.Model):
...
trunk_circle = models.ForeignKey('Trunk_Circle', null=True)
class Trunk_Circle(models.Model):
...
def create_branch_circle(self):
branch_circle = Branch_Circle(trunk_circle=self)
branch_circle.save()
return branch_circle
Using shell I instantiate a Trunk_Circle object first, then call its 'create_branch_circle' method and expect it to create a Branch_Circle object. It doesn't:
import Trunk_Circle
import Branch_Circle
r = Trunk_Circle
s = r.create_branch_circle
When I call Branch_Circle.objects.all() it is empty. Also, the type of 's' is <bound method Trunk_Circle.create_branch_circle of <Trunk_Circle: Trunk_Circle object>>
To instantiate an object or call a method you have to use brackets ():
r = Trunk_Circle()
s = r.create_branch_circle()
How come the length Current_Stock.open can be greater than 0 if I just created the instance of the class?
def initialize_stock(row):
Current_Stock=Stock()
print len(Current_Stock.open)
do some stuff than return object
Loop that calls initializer
for row in xrange(1,sheet.nrows,25):
New_Stock= Stock() #create new instance of class
New_Stock= initialize_stock(row)
stocks.append(New_Stock) #add instance to stocks array
Stock class
class Stock:
name=''
date=[]
open=[]
high=[]
low=[]
close=[]
percent_change_price=[]
percent_change_volume= []
The reason is, that your attributes are not instance variables, but class attributes.
You declared them on class level -- and in Python this means, that they are class attributes by default.
Only variables that are created inside methods are instance variables and also they must be always used with "self." prefix, e.g.:
def __init__(self):
...
self.open = []
...
Could someone translate this Java Pseudo code with generics to Django models? I don't understand the content type concept. It would also be possible to leave out the map and just have a list of KeyValuePairs or KeyValueExamples.
class Dictionary<T extends KeyValuePair>
class KeyValuePair
String key
String value
class KeyValueExample extends KeyValuePair
String example
class Container
Dictionary<KeyValuePair> itemsOne
Dictionary<KeyValueExample> itemsTwo
Django's contenttypes doesn't have anything common with generics from Java. Python has a dynamic type system so there is no need for generics.
This means that you can put any object of any class into the dictionary:
class Container(object):
def __init__(self):
self.itemsOne = {}
self.itemsTwo = {}
container = Container()
container.itemsOne['123'] = '123'
container.itemsOne[321] = 321
container.itemsTwo[(1,2,3)] = "tuple can be a key"
If you want to implement your classes in django models then code could be something like this:
class KeyValuePairBase(models.Model):
key = models.CharField(max_length=30)
value = models.CharField(max_length=30)
class Meta:
abstract = True
class KeyValuePair(KeyValuePairBase):
pass
class KeyValueExample(KeyValuePairBase):
example = models.CharField(max_length=30)
class Container(models.Model):
items_one = models.ManyToManyField(KeyValuePair)
items_two = models.ManyToManyField(KeyValueExample)
# usage of these models
kvp = KeyValuePair.objects.create(key='key', value='value')
kve = KeyValueExample.objects.create(key='key', value='value',
example='Example text')
container = Container.objects.create()
container.items_one.add(kvp)
container.items_two.add(kve)
since four days I'm trying to figure out how to follow a reference from one to another class, starting from the class which is beeing referenced. In SQL-Django there is a related_name to achieve this...
For example I have this class:
class MyClass(Document):
...
other_classes = ListField(ReferenceField(Other_Class))
and this one:
class Other_Class(Document):
...
Now I want to go from Other_Class to MyClass... Any ideas?
Thanks,
Ron
Here is a test case showing how to query it:
import unittest
from mongoengine import *
class StackOverFlowTest(unittest.TestCase):
def setUp(self):
conn = connect(db='mongoenginetest')
def test_one_two_many(self):
class MyClass(Document):
other_classes = ListField(ReferenceField("OtherClass"))
class OtherClass(Document):
text = StringField()
MyClass.drop_collection()
OtherClass.drop_collection()
o1 = OtherClass(text='one').save()
o2 = OtherClass(text='two').save()
m = MyClass(other_classes=[o1, o2]).save()
# Lookup MyClass that has o1 in its other_classes
self.assertEqual(m, MyClass.objects.get(other_classes=o1))
# Lookup MyClass where either o1 or o2 matches
self.assertEqual(m, MyClass.objects.get(other_classes__in=[o1, o2]))
The main question is do you need to store a list of references in the MyClass? It might be more efficient to store the relationship just on OtherClass..
Try this query:
oc = Other_Class()
MyClass.objects.find( other_classes__all = [oc.id] )
While thinking about my problem I came up with a solution.
I just add the ID of my referenced class to my model.
Here's an example:
class MyClass(Document):
...
other_classes = ListField(ReferenceField(Other_Class))
class Other_Class(Document):
myclass = ReferenceField(MyClass)
I'm not quite sure if this is the Mongo-way to do it but I'm pretty sure it works :)
Optionally you can omit the other_classes attribute in MyClass to avoid redundancy but then you need a query like this to get the "child" objects:
Other_Class.objects(myclass = myclass.id)