Prevent Class From Sharing Sub-Class in Python? - python-2.7

I have the following code, while it isn't my actual code it shows the problem I'm having:
class SubObject:
value = None
class Object:
subObject = SubObject()
object0 = Object()
object0.subObject.value = 'hello'
object1 = Object()
object1.subObject.value = 'world'
print object0.subObject.value + ' ' + object1.subObject.value
I have a class SubObject that is used in another class Object but when I create two Object variables they share the same instance of SubObject. This has been causing me plenty of frustration and my actual code really needs the class-in-class, so refactoring into one massive class isn't really what I want to do.
Running the above code in python 2 prints world world

Initialize the data members of the classes using proper constructors. This would be one way to solve this:
class SubObject:
def __init__ (self):
self.value = None
class Object:
def __init__ (self):
self.subObject = SubObject()
object0 = Object()
object0.subObject.value = 'hello'
object1 = Object()
object1.subObject.value = 'world'
print object0.subObject.value + ' ' + object1.subObject.value
The output for this program is:
hello world

Related

how bounding static method in python?

I'm getting this error:
unbound method hello() must be called with A instance as first argument(got nothing instead)
import B
class A():
#staticmethod
def newHello():
A.oldHello() # Here the error
print ' world'
def inject(self):
A.oldHello = B.hello
B.hello = A.newHello
A().inject()
B.hello()
B.py contain only a function "hello" that print "hello"
def hello():
print 'hello'
Thanks in advance
A.oldhello() is not static. So in B's hello function is referencing A's nonstatic oldhello statically. A does in fact need an instance. I'm not too good with the decorators and how they work but maybe try declaring oldhello in the class before the function and calling it #staticmethod. I don't know if the staticness carries over if you override the method.
Try this:
class B():
def hello(self):
print "hello"
class A():
#staticmethod
def newHello(self):
A.oldHello(self) # Here the error
print ' world'
def inject(self):
A.oldHello = B.hello
B.hello = A.newHello
A().inject()
B().hello()

Python Dynamic Subclassing

Possible duplicates:
Is there a way to create subclasses on-the-fly?
Dynamically creating classes - Python
I would like to create a subclass where the only difference is some class variable, but I would like everything else to stay the same. I need to do this dynamically, because I only know the class variable value at run time.
Here is some example code so far. I would like FooBase.foo_var to be "default" but FooBar.foo_var to be "bar." No attempt so far has been successful.
class FooBase(object):
foo_var = "default"
def __init__(self, name="anon"):
self.name = name
def speak(self):
print self.name, "reporting for duty"
print "my foovar is '" + FooBase.foo_var + "'"
if __name__ == "__main__":
#FooBase.foo_var = "foo"
f = FooBase()
f.speak()
foobarname = "bar"
#FooBar = type("FooBar", (FooBase,), {'foo_var': "bar"})
class FooBar(FooBase): pass
FooBar.foo_var = "bar"
fb = FooBar()
fb.speak()
Many thanks
EDIT so I obviously have a problem with this line:
print "my foovar is '" + FooBase.foo_var + "'"
The accepted answer has self.foo_var in the code. That's what I should be doing. I feel ridiculous now.
What about this:
def make_class(value):
class Foo(object):
foo_var = value
def speak(self):
print self.foo_var
return Foo
FooBar = make_class("bar")
FooQux = make_class("qux")
FooBar().speak()
FooQux().speak()
That said, can't you make the value of foo_var be a instance variable of your class? So that the same class instantiated with different input behaves in different ways, instead of creating a different class for each of those different behaviours.

What is the most Pythonic way of implementing classes with auto-incrementing instance attributes?

I have several classes. The desired behavior on an instance creation is that an instance is assigned an ID. For simplicity, let us assume that IDs should start at 0 and increase by 1 with every instance creation. For each of these several classes, the IDs should be incremented independently.
I know how to do this in C++. I have actually also done that in Python, but I do not like it as much as the C++ solution, and I am wondering whether it is due to my limited knowledge of Python (little more than 6 weeks), or whether there is a better, more Pythonic way.
In C++, I have implemented this both using inheritance, and using composition. Both implementations use the Curiously Recurring Template Pattern (CRPT) idiom. I slightly prefer the inheritance way:
#include <iostream>
template<class T>
class Countable{
static int counter;
public:
int id;
Countable() : id(counter++){}
};
template<class T>
int Countable<T>::counter = 0;
class Counted : public Countable<Counted>{};
class AnotherCounted: public Countable<AnotherCounted>{};
int main(){
Counted element0;
Counted element1;
Counted element2;
AnotherCounted another_element0;
std::cout << "This should be 2, and actually is: " << element2.id << std::endl;
std::cout << "This should be 0, and actually is: " << another_element0.id << std::endl;
}
to the composion way:
#include <iostream>
template<class T>
class Countable{
static int counter;
public:
int id;
Countable() : id(counter++){}
};
template<class T>
int Countable<T>::counter = 0;
class Counted{
public:
Countable<Counted> counterObject;
};
class AnotherCounted{
public:
Countable<AnotherCounted> counterObject;
};
int main(){
Counted element0;
Counted element1;
Counted element2;
AnotherCounted another_element0;
std::cout << "This should be 2, and actually is: " << element2.counterObject.id << std::endl;
std::cout << "This should be 0, and actually is: " << another_element0.counterObject.id << std::endl;
}
Now, in python, there are no templates which would give me different counters for each class. Thus, I wrapped the countable class to a function, and obtained the following implementation: (inheritance way)
def Countable():
class _Countable:
counter = 0
def __init__(self):
self.id = _Countable.counter
_Countable.counter += 1
return _Countable
class Counted ( Countable() ) :
pass
class AnotherCounted( Countable() ):
pass
element0 = Counted()
element1 = Counted()
element2 = Counted()
another_element0 = AnotherCounted()
print "This should be 2, and actually is:", element2.id
print "This should be 0, and actually is:", another_element0.id
and the composition way:
def Countable():
class _Countable:
counter = 0
def __init__(self):
self.id = _Countable.counter
_Countable.counter += 1
return _Countable
class Counted ( Countable() ) :
counterClass = Countable()
def __init__(self):
self.counterObject = Counted.counterClass()
class AnotherCounted( Countable() ):
counterClass = Countable()
def __init__(self):
self.counterObject = self.counterClass()
element0 = Counted()
element1 = Counted()
element2 = Counted()
another_element0 = AnotherCounted()
print "This should be 2, and actually is:", element2.counterObject.id
print "This should be 0, and actually is:", another_element0.counterObject.id
What troubles me is this. In C++, I have a good idea what I am doing, and e.g. I see no problems even if my classes actually inherit multiply (not just from Countable<> templated class) - everything is very simple.
Now, in Python, I see the following issues:
1) when I use composition, I instantiate the counting class like that:
counterClass = Countable()
I have to do this for every class, and this is possibly error-prone.
2) when I use inheritance, I will bump to further troubles when I will want to ihnerit multiply. Note that above, I have not defined the __init__'s of Counted nor of AnotherCounted, but if I inherited multiply I would have to call base class constructors explicitly, or using super(). I do not like this (yet?) I could also use metaclasses, but my knowledge is limited there and it seems that it adds complexity rather than simplicity.
In conclusion, I think that composition way is probably better for Python implementation, despite the issue with having to explicitly define the counterClass class attribute with Countable().
I would appreciate your opinion on validity of my conclusion.
I would also appreciate hints on better solutions than mine.
Thank you.
I would use __new__, that way you don't have to remember doing anything in __init__:
class Countable(object):
counter = 0
def __new__(cls, *a, **kw):
instance = super(Countable, cls).__new__(cls, *a, **kw)
instance.id = cls.counter + 1
cls.counter = instance.id
return instance
class A(Countable):
pass
class B(Countable):
pass
print A().id, A().id # 1 2
print B().id # 1
I might use a simple class decorator ...
import itertools
def countable(cls):
cls.counter = itertools.count()
return cls
#countable
class Foo(object):
def __init__(self):
self.ID = next(self.__class__.counter)
#countable
class Bar(Foo):
pass
f = Foo()
print f.ID
b = Bar()
print b.ID
If you really want to do this the "fancy" way, you could use a metaclass:
import itertools
class Countable(type):
def __new__(cls,name,bases,dct):
dct['counter'] = itertools.count()
return super(Countable,cls).__new__(cls,name,bases,dct)
class Foo(object):
__metaclass__ = Countable
def __init__(self):
self.ID = next(self.__class__.counter)
class Bar(Foo):
pass
f = Foo()
print f.ID
b = Bar()
print b.ID

Accessing static method variables from another static method in the same class

Facing the error as :
AttributeError: 'function' object has no attribute 'd'.
how to access the dictionary?
code:
class A:
#staticmethod
def test():
d = {}
d['a'] = 'b'
print d
#staticmethod
def test1():
d1 = {}
d1['a'] = 'c'
if (A.test.d['a'] == A.test1.d1['a']):
print "yes"
else:
print "Oh No!!"
A.test()
A.test1()
Check out this on the matter of static variables in Python.
You should be able to sort it out using A.d and A.d1 whenever you wish to use the static variables. Note that, as you have them, they are local to test and test1, respectively. If you want them to be static, you have to declare them inside the class scope, but not within any function definition.

MongoDB - MongoEngine - How do I follow a reference from "the other side"?

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)