Python:Initialize a list in a class constructor - python

I am trying to initialize a list in a class like this:
class Node():
def __init__(self):
self.info = None
self.word = ''
for i in range(256):
self.ptrs[0] = None
if __name__ == '__main__':
n = Node()
Now this throws an error
self.ptrs[0] = None
AttributeError: Node instance has no attribute 'ptrs'
I am sure that I'm missing something stupid. What is it?

I think you want this:
class Node():
def __init__(self):
self.info = None
self.word = ''
self.ptrs = [None]*256

Related

Anytree NodeMixin

I want to use the NodeMixin Module, but it's not really clear to me if I read the documentation how to do that.
https://anytree.readthedocs.io/en/2.8.0/api/anytree.node.html#anytree.node.nodemixin.NodeMixin
I have a BaseClas like this:
from anytree import NodeMixin, RenderTree
class Tree():
def __init__(self, data, parent):
self.data = data
self.parent = parent
self.children = []
def __eq__(self, other):
if isinstance(other, Tree):
return self.data == other.data
else:
return False
def __repr__(self):
return "Tree("+str(self.data)+","+str(self.children)+")"
def __str__(self):
return self.__repr__()
def update_parent(self, new):
self.parent = new
def add_child(self, c):
self.children.append(c)
def rm_child(self, c):
self.children.remove(c)
If I want to use the NodeMixin Module I would need something like this:
class TreeMix(Tree, NodeMixin): # Add Node feature
def __init__(self, name, length, width, parent=None, children=None):
super(TreeMix, self).__init__()
self.name = name
self.length = length
self.width = width
self.parent = parent
if children:
self.children = children
I get this Error Message:
init() missing 2 required positional arguments: 'data' and 'parent'
I create Objects like this:
my0 = TreeMix('0', 0, 0, parent=None)
my1 = TreeMix('1', 1, 0, parent=my0)
my2 = TreeMix('2', 2, 0, parent=my1)
Did I get the Constructor wrong?

How to clear inner class attributes on parent creation

I have a nested class setup like the code snippet bellow.
class test:
class child:
some_variable = None
When I try to call this code from another .py file like bellow
from testing import test
t = test()
t.child.some_variable ="123"
t = test()
print(t.child.some_variable)
I get the output
123
I expected to get None, or at least an error message. I have tried to solve it with the following approach but the problem persists with the same output.
class test:
def __init__(self):
self.child()
class child:
some_variable = None
def __init__(self):
self.some_variable = ""
How can I initiate a new child class when I am calling the parent class?
By don't having it as an inner class, but as a separate class and then an instant attribute:
class child_class:
def __init__(self):
self.some_variable = None
class test:
def __init__(self):
self.child = child_class()
t = test()
t.child.some_variable = "123"
t = test()
print(t.child.some_variable) # prints None
Or alternative you can have a inner class, but still you have to create an instance attribute:
class test:
class child_class:
def __init__(self):
self.some_variable = None
def __init__(self):
self.child = self.child_class()
t = test()
t.child.some_variable = "123"
t = test()
print(t.child.some_variable) # also prints None

Python class property error AttributeError: can't set attribute

class DockerEngine(Device):
def __init__(self):
super(DockerInfo, self).__init__()
self.docker_id = None
self.host_ip_address = None
self.total_containers = 0
self.running_containers = 0
self.paused_containers = 0
self.stopped_containers = 0
#property
def host_ip_address(self):
return self._host_ip_address
#host_ip_address.setter
def host_it_address(self, ip):
self._host_ip_address = ip
#property
def docker_id(self):
return self._docker_id
#docker_id.setter
def docker_id(self, id):
self._docker_id = id
When I initialize a DockerEngine object, it complains that in __init__ self.host_ip_address, can't set attribute.
Your code has a typo
Change host_it_address to host_ip_address.
#host_ip_address.setter
def host_it_address(self, ip): <--- WRONG FUNCTION NAME
self._host_ip_address = ip

Creating python objects of same type from nested class

My List class has a nested _Node class within it. With these 2 classes, I can:
Initialize an object of type List within List.
Initialize an object of type _Node within List.
Initialize an object of type List within _Node.
I can't, however, initialize a _Node within a _Node. The last line of the code is below causes NameError: global name '_Node' is not defined
class List:
def __init__(self):
self.root = None
self.brother = None
def set_root(self):
self.root = self._Node()
def set_brother(self):
self.brother = List()
def set_root_next(self):
self.root.set_next()
class _Node:
def __init__(self, next_node=None, data=None):
self.next_node = next_node
self.data = data
def set_next(self):
self.next_node = _Node()
if __name__ == '__main__':
x = List()
x.set_root()
x.set_brother()
x.set_root_next()
How do I solve this? Making the _Node class unnested works but I am planning to have many types of list in the same file. All accompanying nodes will inherit from a single abstract class so keeping this structure is important.
Try using self.__class__() instead
class List:
def __init__(self):
self.root = None
self.brother = None
def set_root(self):
self.root = self._Node()
def set_brother(self):
self.brother = List()
def set_root_next(self):
self.root.set_next()
class _Node:
def __init__(self, next_node=None, data=None):
self.next_node = next_node
self.data = data
def set_next(self):
self.next_node = self.__class__()
if __name__ == '__main__':
x = List()
x.set_root()
x.set_brother()
x.set_root_next()

Python Self Replicating Class

I am messing about with having a class recreate itself. I am trying to get an understanding of metaclass attribute but I am still not 100% clear.
The Goal:
A Class that creates itself for some iteration and then holds its first degree of children it created (In the example below that is one object in self.children).
class MyClass(object):
def __init__(self, num):
self.name = num
self.children = []
if num !=0:
cls = self.__new__(self.__class__ )
cls = self.__init__(num-1)
self.children.append(cls)
#Uncomment for Error
#print cls.name
if __name__ == "__main__":
c = MyClass(3)
This is what I am trying but trying to print self.name of the new object returns a kind AttributeError that "name" does not exist. I think its because I am not passing a dict of the attributes but I am looking for some clarifications of best practice and maybe a solution.
If I was not clear on something please let me know so I can better explain!
There's no need to call the __new__() or __init__() methods yourself; the constructor will handle that part automagically.
class MyClass(object):
def __init__(self, num):
self.name = num
self.children = []
if num !=0:
cls = self.__class__(num-1)
self.children.append(cls)
print cls.name
How about:
class MyClass(object):
def __init__(self, num):
self.name = num
self.children = []
if num != 0:
self.children.append(self.__class__(num - 1))
if __name__=="__main__":
c = MyClass(3)

Categories