Python class not intitializing itself to empty - python-2.7

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 = []
...

Related

Can I use a dictionary to call methods from different classes that inheritate from the same class?

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.

How to replace __prepare__ for metaclass in python 2

I need to convert some code from python 3 to python 2. I have a metaclass where the __prepare__ method sets up a function in the class dict. I tried to translate to a __new__ method but I am unable to set up the SET_DEFAULTS function. Is that possible ?
I have a NameError: name 'SET_DEFAULTS' at initialization
class UazeMessageMeta (type):
#staticmethod
def __prepare__(name, bases, **kwargs):
d = {}
for b in bases:
if 'DEFAULT_VALUES' in dir(b):
d.update(b.DEFAULT_VALUES)
return {
'SET_DEFAULTS' : lambda **kwargs : d.update(kwargs),
'DEFAULT_VALUES' : d
}
class UazeMessage (bytearray):
"""
A basic message (header only). This class also provides the
base behavior for all messages.
"""
# gp test py27 -----------------
__metaclass__ = UazeMessageMeta
# ------------
priority = MessageField(0, 1, Priority)
sequence = MessageField(1, 7, FieldType.UNSIGNED)
readWrite = MessageField(8, 1, ReadWriteFlag)
ack = MessageField(9, 2, Ack)
channel = MessageField(11, 2, FieldType.UNSIGNED)
category = MessageField(13, 3, Category)
item = MessageField(16, 8, FieldType.UNSIGNED)
DEFAULT_SIZE = 3
def __init__(self, init=0, setdefaults=None, **kwargs):
# If init is still or None, initialize the size of the message
# using the default size provided in the class.
if init == None or init == 0:
init = type(self).DEFAULT_SIZE
super(UrmpMessage,self).__init__(init)
# Set any default or provided fields.
initval = {}
if (isinstance(init, int) and setdefaults != False) or \
(setdefaults == True):
initval = dict(self.DEFAULT_VALUES)
initval.update(kwargs)
for key, value in initval.items():
setattr(self, key, value)
class ResetBase (UazeMessage):
"""Reset response/request structure."""
resetType = MessageField(24, 8, ResetType)
SET_DEFAULTS(
category = Category.OPERATION,
resetType = ResetType.SOFT,
item = 0)
DEFAULT_SIZE = 4
Ordinarily, you can't do that.
The introduction of __prepare__ is a fundamental change in Python3, which allows the customization of the namespace where a class body itself is parsed.
I believe the main motivation doing that was to provide a way to replace the local namespace inside a class body with an OrderedDict, so that the class initialization (in the metaclass __new__ or __init__ methods) could benefit from the declaration order of methods and attributes inside the class body. It should be considered that as of Python 3.6 (final version due this week), an ordered dictionary is used by default in the class body, and a metaclass is no longer necessary for that.
The __prepare__ mechanism is way more flexible than that, and in a simpler use, allow one to simply pre-populate the class body dictionary with predetermined values. That is what your project do.
However, since this code does not need an special dictionary class, and just pre-populate an ordinary dictionary, all you need to do is to write an ordinary function that takes in a dictionary and base classes as parameters, and fills in that dictionary according to the existing code in the __prepare__ method. Then, call that function in the beggining of a class body, passing in the dictionary returned by the locals() call as parameter. That is it: the class body namespace can be pre-filled in the sameway.
def prepare(bases, dct):
for base in bases:
dct["special_attribute"] = {}
if "special_attribute" in base.__dict__:
dct["special_attribute" ].update(base.__dict__["special_attribute"])
...
class MyClass(bytearray):
prepare((bytearray,), locals())
...
All that said, I really advise you to try if possible NOT to backport a project to Python2 at this point in time - it will just complicate your codebase - and give up using new features in a consistent way (for example, this tip above instead of __prepare__ )

how to establish what is the parent of a native widget gtk3

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

instance creating instances

How can I create an instance which creates as many instances as I want?
I think I have to create a class Manager for example and inside that class with an aggregation relationship to create the class name salary and bottles.
I want to create an instance of Manager which creates as many instances of bottle and salary I want. How can I do that?
It's called a factory and it looks something like:
class Factory {
Product create(int n);
// ...
}
class Product {
// ...
}
class Prod1 : public Product {
// ...
}
int main() {
Factory factory = Factory();
Product prod[10] = factory.create(10);
// ...
with create simply returning a Product object of some derived type. Of course, there's usually some context passed into the Factory::create function to hint at the type of Product you want.
Use pointers. You can have a pointer which points to as many instances as you want and new them whenever you want.

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.