How to reference an instance variable in Python - python

I defined an instance variable in the init() method of a class and derived a new class from it. When I try to reference this variable from an instance of the secondary class, it seems it was not inherited.
This is the code:
company=Company()
person=Person()
task=Task()
print(company.get_attrs())
class Entity(Persistent):
list_of_attrs=[]
list_of_attrs_flag=False
def __init__(self):
attributes={}
attributes_edition_flag={}
if not type(self).list_of_attrs_flag:
type(self).list_of_attrs=self.get_attrs_from_persistent()
type(self).list_of_attrs_flag=True
for attr in type(self).list_of_attrs:
attributes[attr]=''
attributes_edition_flag[attr]='false'
def get_attrs(self):
return(self.attributes)
class Company(Entity):
def hello(self):
print('hello')
This is the error I get:
MacBook-Pro-de-Hugo:Attractora hvillalobos$ virtual/bin/python3 control.py
Traceback (most recent call last):
File "control.py", line 7, in <module>
print(company.get_attrs())
File "/Users/hvillalobos/Dropbox/Code/Attractora/model.py", line 48, in get_attrs
return(self.attributes)
AttributeError: 'Company' object has no attribute 'attributes'
It was working but I moved something (I guess), but I can't find what.
Thanks for your help

In your __init__ method, you have to use self.attributes, not attributes.

Related

How is HttpResponseRedirectBase class being called when I call HttpResponseRedirect

I am trying to figure out how HttpResponseRedirectBase is being called when I call this
return HttpResponseRedirect(next_page, context)
I believe this question has more to do with python than Django but I cannot find the answer to this question.I understand that in python the derived class needs to explicitly call the __init__ of the base class in order to initialize it.So far this is what I have seen
class HttpResponseRedirect(HttpResponseRedirectBase):
status_code = 302
Now my question is how is the initializer of HttpResponseRedirectBase being called here ? I tried simulating the above situation
class foo(object) :
def __init__(self,par):
print "Inside foo constructor"
class bar(foo):
status_code = 302
b = bar(23)
I am not sure how init of foo will be called in this case ? In this case I get the error
Traceback (most recent call last):
File "python", line 5, in <module>
TypeError: Error when calling the metaclass bases
function() argument 1 must be code, not str
Any help clearing this out would be appreciated.
You are trying to inherit a function
class bar(foo):
Where foo is function.Did you mean
class foo(object) :
def __init__(self,par):
print "Inside foo constructor"

exceptions.AttributeError: class KeyAgent has no attribute 'delele_customer_node()'

I've 2 files: customer.py & agent.py. It looks like this:
customer.py:
from agent import KeyAgent
class CustomerController(object):
def __init__(self, container):
self.key = container.agent
def delete(self, path):
KeyAgent.delele_customer_node()
agent.py:
class KeyAgent(service.Service):
def __init__(self):
pass
def delele_customer_node():
....
Python is throwing this exception while running:
exceptions.AttributeError: class KeyAgent has no attribute 'delele_customer_node()'
Even though I've imported KeyAgent class from agent.py why method delele_customer_node() is not accessible from delete() of customer.py?
You must have misspelled the method name (delele? or delete?). The KeyAgent class does have a method delete_customer_node (I will assume that was a typo).
>>> class KeyAgent(object):
... def delete_customer():
... pass
...
>>> KeyAgent.delete_customer
<unbound method KeyAgent.delete_customer>
That means, the method is there. However your code is quite broken. Unless you use the staticmethod or classmethod decorators, the first argument of a method "must be" self, and you need to instantiate the class to call it. See what happens if you try to call this method directly:
>>> KeyAgent.delete_customer()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method delete_customer() must be called with KeyAgent instance as first argument (got nothing instead)

Python: calling overriden base class method in base class init [duplicate]

This question already has an answer here:
I can't get super() to work in python 2.7
(1 answer)
Closed 8 years ago.
Consider the following classes, running python2.7:
class S(object):
def __init__(self):
print 'Si'
self.reset()
def reset(self):
print 'Sr'
self.a=0
class U1(S):
def reset(self):
print 'U1r'
self.b=0
super(S,self).reset()
The desired functionality is that
creating an instance of the base class calls its reset method;
creating an instance of the derived class calls its reset method, and also invokes the base class's reset method.
I get (1):
>>> print S().a
Si
Sr
0
but not (2):
>>> print U1().b
Si
U1r
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "tt.py", line 4, in __init__
self.reset()
File "tt.py", line 14, in reset
super(S,self).reset()
AttributeError: 'super' object has no attribute 'reset'
What's the cleanest way to get what I want? I presume the error has something to do with the order in which class membership is getting constructed, but I can't figure it out from the documentation. . .
You should be calling super(U1, self).reset() in U1.reset(). When you use super, you should always pass the name of the current class as the first argument, not the name of the parent class. As stated in the docs:
super(type[, object-or-type])
Return a proxy object that delegates method calls to a parent or sibling class of type
super will look up the method on the parent or sibling of the type you provide. When you provide the parent class, it will try to find implementations of reset on parents/siblings of the parent, which will fail.
Should be:
super(U1, self).reset()
In my head, I read "super(U1,..." as "parent of U1" to keep it straight.

Python: how to automatically create an instance in another class

In writing a Python (2.5) program, I tried to create a class and, in its __init__ function, automatically create an instance of another class with its name as an argument to the __init__ function, something like this:
class Class1:
def __init__(self,attribute):
self.attribute1=attribute
class Class2:
def __init__(self,instanceName):
#any of Class2's attributes
exec instanceName + '=Class1('attribute1')'
# this should produce an instance of Class1 whose name is instanceName
But when I make an instance of Class2, instance=Class2('instance2'), and try to get attribute1 of instance2 (which should have been created from Class2's __init__ function) I get an error message:
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
print instance2.attribute1
NameError: name 'instance2' is not defined
I don't know what the problem is, since name='instance3' and
exec name+'=Class1('attribute1') does work, though this is probably because I don't have much experience with Python. How would I be able to do something like this automatically when an instance is created?
I have to run, so hopefully, someone else can fix any mistakes in this post:
class Class1:
def __init__(self, attribute):
self.attribute1 = attribute
class Class2:
def __init__(self, instanceName):
setattr(self, instanceName, Class1(...)) # replace ... with whatever parameters you want

Why am I unable to perform a simple operation in the __init__ of my class?

Given below is a snippet from a class of which I am trying to create objects and getting error:
class FoF(object):
def __init__(self,path):
filepath=[]
filepath.append(self.FileOrFolder(path))
Upon executing which I get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "PathOps.py", line 6, in __init__
def __init__(self,path):
NameError: global name 'filepath' is not defined
After which I tried:
filepath=[]
class FoF(object):
def __init__(self,path):
global filepath.append(self.FileOrFolder(path))
And again:
File "<stdin>", line 1, in <module>
File "PathOps.py", line 6, in __init__
global filepath.append(self.FileOrFolder(path))
NameError: global name 'filepath' is not defined
What is causing the error and how do I fix it?
Try using insted of global the special word self.
So something like this
class FoF(object):
def __init__(self,path):
self.filepath=[]
self.filepath.append(self.FileOrFolder(path))
The reason this error comes up is because what python thinks you're trying to do is one of two things:
Either you're trying to reference a global variable called filepath -- which is clear that's not what you're trying
What's not so clear is that you could also define a class attribute called filepath -- the only problem with that is that you can't define a class attribute with a function of that class. You can only do so within the class -- outside a class function
So in order to declare variables within a function you have to use the word self before it.
Edit** if you want it to be an attribute of the class -- as I'm assuming is what you meant you could do so like this:
class FoF(object):
filepath=[]
def __init__(self,path):
self.filepath.append(self.FileOrFolder(path))
I don't think you're giving us enough information. For example:
>>> class FoF(object):
... def __init__(self, path):
... junk = []
... junk.append(path)
...
>>> foo = FoF('bar/path')
produces no error.
What, exactly, are you trying to do?

Categories