Instances ship attributes to other instances after construction - python-3.x

I was looking for a way to access configuration file entries from instance- resp. class-bound variables. Therefor I have created the following module:
from ..lib.files import ConfigFile
from abc import abstractmethod
__all__ = ['ClassConfig',
'InstanceConfig',
'Configurable']
class ConfigEntry():
"""
A Config entry
"""
__value = None
def __init__(self, value=None):
"""
Initializes the
"""
self.__value = value
def __set__(self, __, value):
self.__value = value
#property
def value(self):
"""
Returns the value
"""
return self.__value
class ClassConfig(ConfigEntry):
"""
A class config entry
"""
def __get__(self, obj, cls):
"""
Returns its value, when called by a class, else itself
"""
if obj == None:
return self.value
else:
return self
class InstanceConfig(ConfigEntry):
"""
An instance config entry
"""
def __get__(self, obj, cls):
"""
Returns its value, when called by an instance, else itself
"""
if obj != None:
return self.value
else:
return self
class Configurable():
"""
Configuration file binding
"""
__SUFFIX = '.conf'
__TYPES = {int: 'int',
float: 'float',
str: 'str',
bool: 'bool'}
__file_ = None
__lbi = '['
__lei = ']'
__ls = ','
__ts = '←'
__loaded = False
def __init__(self, path, suffix=None):
"""
Initialize the config file
"""
# Initializes instance methods
self.__setinstattr()
suffix = suffix if suffix != None else self.__SUFFIX
self.__file_ = ConfigFile(path + suffix)
self.load()
def __setinstattr(self):
"""
Set instance attributes
"""
self.__fields = self.__inst___fields
self._file = self.__inst____file
self._force_load = self.__inst__force_load
self.load = self.__inst_load
self.store = self.__inst_store
#staticmethod
def __filter(attrs):
return [a for a in attrs
if a == a.upper()
and not a.startswith('_')]
#staticmethod
def __encode(val):
"""
Encode a value
"""
t = type(val)
if t == list:
return Configurable.__lbi + \
Configurable.__ls.join([Configurable.__encode(i)
for i in val]) \
+ Configurable.__lei
elif val == None:
return None
else:
return Configurable.__ts.join([str(val),
Configurable.__TYPES.get(t, '?')])
#staticmethod
def __decode(val):
"""
Decode a value
"""
def det_type(token):
"""
Determine the type of a token
"""
t = token.strip().split(Configurable.__ts)
if len(t) == 2:
raw_val = t[0]
tpe = t[1]
if tpe == Configurable.__TYPES[str]:
return str(raw_val)
elif tpe == Configurable.__TYPES[int]:
return int(raw_val)
elif tpe == Configurable.__TYPES[float]:
return float(raw_val)
elif tpe == Configurable.__TYPES[bool]:
return True if raw_val.lower() in ['1',
'true',
't'] else False
else:
try:
return int(raw_val)
except:
try:
return float(raw_val)
except:
return raw_val
return token
def str2list(s):
"""
Try to parse a list from a string
"""
def getlist(val):
"""
Get a list from a reversed character list of a string
"""
result = []
token = ''
while val:
c = val.pop()
if c == Configurable.__lei:
token = Configurable.__lei
result = [getlist(val)] + result
elif c == Configurable.__lbi:
if (not Configurable.__lbi in token) and (not Configurable.__lei in token):
result = [det_type(token)] + result
token = c
return result
elif c == Configurable.__ls:
if (not Configurable.__lbi in token) and (not Configurable.__lei in token):
result = [det_type(token)] + result
token = ''
else:
token = c + token
if token:
result = [det_type(token)] + result
return result
l = []
for char in s:
l.append(char)
l = getlist(l)
if len(l) == 0:
return l
return l.pop()
return str2list(val)
#classmethod
def __fields(cls):
"""
Get fields for an instance
"""
result = {}
class Subclass(cls):
def __init__(self):
pass
instance = Subclass()
attrs = Configurable.__filter(dir(instance))
for a in attrs:
aval = getattr(instance, a)
if isinstance(aval, ClassConfig):
value = getattr(cls, a)
result[a] = value
return result
def __inst___fields(self):
"""
Get fields of an instance
"""
result = {}
cls = self.__class__
attrs = Configurable.__filter(dir(cls))
for a in attrs:
val = getattr(cls, a)
if isinstance(val, InstanceConfig):
value = getattr(self, a)
result[a] = value
return result
#classmethod
#abstractmethod
def _file(cls):
"""
Returns the file
XXX: Implement by calling
super()._file(static_path)
"""
pass
#classmethod
def _file_path(cls, path, suffix=None):
"""
Returns the file relative to a path
"""
suffix = suffix if suffix != None else cls.__SUFFIX
f = ConfigFile(path + suffix)
f.create()
return f
def __inst____file(self):
"""
Returns the file
"""
return self.__file_
#classmethod
def load(cls):
"""
Loads the config file content, if not yet done into the class
"""
if not cls.__loaded:
return cls._force_load()
return True
def __inst_load(self):
"""
Loads the config file content, if not yet done into the instance
"""
if not self.__loaded:
return self._force_load()
return True
#classmethod
def _force_load(cls):
"""
Loads the config file's content to the class
"""
if cls._file().exists:
data = cls._file().dict()
for field in Configurable.__filter(data):
setattr(cls, field,
Configurable.__decode(data[field]))
cls.__loaded = True
return True
return False
def __inst__force_load(self):
"""
Loads the config file's content to the instance
"""
if self._file().exists:
data = self._file().dict()
for field in Configurable.__filter(data):
setattr(self, field,
Configurable.__decode(data[field]))
self.__loaded = True
return True
return False
#classmethod
def store(cls):
"""
Writes class config to file
"""
result = True
content = cls.__fields()
if not cls._file().exists:
cls._file().create()
for new_field in content:
set_result = cls._file().set(new_field,
Configurable.__encode(content[new_field]))
result = False if not set_result else result
return result
def __inst_store(self):
"""
Writes instance config to file
"""
result = True
content = self.__fields()
if not self._file().exists:
self._file().create()
for new_field in content:
set_result = self._file().set(new_field,
Configurable.__encode(content[new_field]))
result = False if not set_result else result
return result
The Configurable class is now inherited by several sub-classes, which may have global configuration (the class-bound stuff) and user-dependen configuration (the instance-bound stuff) like that:
class Spam(Configurable):
EGGS = InstanceConfig('foo')
GLOBAL_EGGS = ClassConfig('bar')
Now I face the problem, that each time a load() is performed on many instances in sequence, the InstanceConfigEntry will copy the value from the previuos instance:
class RETARD(Daemon):
"""
Real Estate Translation, Archiving and Redirection Daemon
"""
__source = None # The source interface instance
__targets = [] # The target interface instances
__locked = False # System locked state flag
__start_time = None # Start time of loop
__sleeping = 0 # Remaining time to sleep
#===========================================================================
# Default customer config
#===========================================================================
SOURCE = InstanceConfig('') # Name of the source interface
TARGETS = InstanceConfig([]) # Names of the target interfaces
INTERVAL = InstanceConfig(120.0) # Loop interval
DEBUG = InstanceConfig(False) # Print the import config?
def __init__(self, customer):
"""
Constructor
"""
print('SOURCE1: ' + str(self.SOURCE))
super().__init__(customer)
print('SOURCE2: ' + str(self.SOURCE))
self.__load()
print('SOURCE3: ' + str(self.SOURCE))
# Disable logger on high level to prevent PyXB
# from printing messages to the terminal
logging.disable(9999)
<SNIP>
When loaded like this (daemons contains four different instances):
daemons = []
for customer in customers:
daemons.append(RETARD(customer))
It will produce this output:
SOURCE1:
SOURCE2: IS24
SOURCE3: IS24
SOURCE1: IS24
SOURCE2: is24
SOURCE3: is24
SOURCE1: is24
SOURCE2: infobase
SOURCE3: infobase
SOURCE1: infobase
SOURCE2: infobase
SOURCE3: infobase
I do not understand this behaviour, since I did not change the class' attributes anywhere but just those of the instances.
How can I avoid the instances to ship their changed attributes to the next instance?

The problem here, wich I did not realize was, that the InstanceConfig and ClassConfig entries as bound to the class at the time, the module is loaded. When I assigned other content to the respective attributes during runtime from within an instance, it of course just changed the content of the still class-bound *Config instance.
I worked arund this issue by defaulting values iff they are not contained within the respective config file like so:
from ..lib.files import ConfigFile
from abc import abstractmethod
__all__ = ['ClassConfig',
'InstanceConfig',
'Configurable']
class ConfigEntry():
"""
A Config entry
"""
__value = None
__default = None
def __init__(self, default=None):
"""
Initializes the
"""
self.__default = default
self.__value = default
def __set__(self, __, value):
"""
Sets the value
"""
self.__value = value
#property
def value(self):
"""
Returns the value
"""
return self.__value
#property
def default(self):
"""
Access default value
"""
return self.__default
class ClassConfig(ConfigEntry):
"""
A class config entry
"""
def __get__(self, obj, cls):
"""
Returns its value, when called by a class, else itself
"""
if obj == None:
return self.value
else:
return self
class InstanceConfig(ConfigEntry):
"""
An instance config entry
"""
def __get__(self, obj, cls):
"""
Returns its value, when called by an instance, else itself
"""
if obj != None:
return self.value
else:
return self
class Configurable():
"""
Configuration file binding
"""
__SUFFIX = '.conf'
__TYPES = {int: 'int',
float: 'float',
str: 'str',
bool: 'bool'}
__file_ = None
__lbi = '[' # List begin identifier
__lei = ']' # List end identifier
__ls = ',' # List separator
__ts = '←' # Type separator
__loaded = False
def __init__(self, path, suffix=None):
"""
Initialize the config file
"""
# Initializes instance methods
self.__setinstattr()
suffix = suffix if suffix != None else self.__SUFFIX
self.__file_ = ConfigFile(path + suffix)
self.load()
def __setinstattr(self):
"""
Set instance attributes
"""
self.__fields = self.__inst___fields
self._file = self.__inst____file
self._force_load = self.__inst__force_load
self.load = self.__inst_load
self.store = self.__inst_store
#staticmethod
def __filter(attrs):
return [a for a in attrs
if a == a.upper()
and not a.startswith('_')]
#staticmethod
def __encode(val):
"""
Encode a value
"""
t = type(val)
if t == list:
return Configurable.__lbi + \
Configurable.__ls.join([Configurable.__encode(i)
for i in val]) \
+ Configurable.__lei
elif val == None:
return None
else:
return Configurable.__ts.join([str(val),
Configurable.__TYPES.get(t, '?')])
#staticmethod
def __decode(val):
"""
Decode a value
"""
def det_type(token):
"""
Determine the type of a token
"""
t = token.strip().split(Configurable.__ts)
if len(t) == 2:
raw_val = t[0]
tpe = t[1]
if tpe == Configurable.__TYPES[str]:
return str(raw_val)
elif tpe == Configurable.__TYPES[int]:
return int(raw_val)
elif tpe == Configurable.__TYPES[float]:
return float(raw_val)
elif tpe == Configurable.__TYPES[bool]:
return True if raw_val.lower() in ['1',
'true',
't'] else False
else:
try:
return int(raw_val)
except:
try:
return float(raw_val)
except:
return raw_val
return token
def str2list(s):
"""
Try to parse a list from a string
"""
def getlist(val):
"""
Get a list from a reversed character list of a string
"""
result = []
token = ''
while val:
c = val.pop()
if c == Configurable.__lei:
token = Configurable.__lei
result = [getlist(val)] + result
elif c == Configurable.__lbi:
if (not Configurable.__lbi in token) and (not Configurable.__lei in token):
result = [det_type(token)] + result
token = c
return result
elif c == Configurable.__ls:
if (not Configurable.__lbi in token) and (not Configurable.__lei in token):
result = [det_type(token)] + result
token = ''
else:
token = c + token
if token:
result = [det_type(token)] + result
return result
l = []
for char in s:
l.append(char)
l = getlist(l)
if len(l) == 0:
return l
return l.pop()
return str2list(val)
#classmethod
def __fields(cls):
"""
Get fields for an instance
"""
result = {}
class Subclass(cls):
def __init__(self):
pass
instance = Subclass()
attrs = Configurable.__filter(dir(instance))
for a in attrs:
aval = getattr(instance, a)
if isinstance(aval, ClassConfig):
result[a] = aval
return result
def __inst___fields(self):
"""
Get fields of an instance
"""
result = {}
cls = self.__class__
attrs = Configurable.__filter(dir(cls))
for a in attrs:
val = getattr(cls, a)
if isinstance(val, InstanceConfig):
result[a] = val
return result
#classmethod
#abstractmethod
def _file(cls):
"""
Returns the file
XXX: Implement by calling
super()._file(static_path)
"""
pass
#classmethod
def _file_path(cls, path, suffix=None):
"""
Returns the file relative to a path
"""
suffix = suffix if suffix != None else cls.__SUFFIX
f = ConfigFile(path + suffix)
f.create()
return f
def __inst____file(self):
"""
Returns the file
"""
return self.__file_
#classmethod
def load(cls):
"""
Loads the config file content, if not yet done into the class
"""
if not cls.__loaded:
return cls._force_load()
return True
def __inst_load(self):
"""
Loads the config file content, if not yet done into the instance
"""
if not self.__loaded:
return self._force_load()
return True
#classmethod
def _force_load(cls):
"""
Loads the config file's content to the class
"""
if cls._file().exists:
data = cls._file().dict()
else:
data = {}
fields = cls.__fields()
for field in fields:
val = data.get(field)
if val == None:
val = fields[field].default
else:
val = Configurable.__decode(val)
setattr(cls, field, val)
cls.__loaded = True
return True
def __inst__force_load(self):
"""
Loads the config file's content to the instance
"""
if self._file().exists:
data = self._file().dict()
else:
data = {}
fields = self.__fields()
for field in fields:
val = data.get(field)
if val == None:
val = fields[field].default
else:
val = Configurable.__decode(val)
setattr(self, field, val)
self.__loaded = True
return True
#classmethod
def store(cls):
"""
Writes class config to file
"""
result = True
fields = cls.__fields()
if not cls._file().exists:
cls._file().create()
for field in fields:
val = fields[field].value
set_result = cls._file().set(field,
Configurable.__encode(val))
result = False if not set_result else result
return result
def __inst_store(self):
"""
Writes instance config to file
"""
result = True
fields = self.__fields()
if not self._file().exists:
self._file().create()
for field in fields:
val = fields[field].value
set_result = self._file().set(field,
Configurable.__encode(val))
result = False if not set_result else result
return result

Related

Class template with methods already defined

I have two methods inside a class (mask_im and save_im) that I must include in several other classes in separate modules. How can I create a class with those two methods without copying and paste 10 lines of code, or at least reduce it to two lines of code? I want to have like a class template or something that I can reuse easily.
class MaskFromImages:
def __init__(self, im_to_mask, m_rules, val_assign=None):
im_mem = ReadMap(im_to_mask, mem=True)
self.reference = im_mem.reference
if im_mem.no_data is None:
self.out_no_data = 255
else:
self.out_no_data = im_mem.no_data
out_array = im_mem.array
out_mem = im_mem.osgeodata
for i in m_rules:
out_array = MaskCls(out_mem, i[0], i[1], val_assign).array
out_mem = save_map(out_array, "", im_mem.d_type, self.reference, format_out="MEM")
out_array = out_array.astype("int16")
self.array = out_array
def mask_im(self, mask_aoi, mask_aoi_vl, replace_im=None, reverse=False):
map_mem = save_map(self.array, "", gdal.GDT_UInt16, self.reference, format_out="MEM")
im_masked = MaskAOI(map_mem, mask_aoi, mask_aoi_vl, self.out_no_data,
replace_im=replace_im, reverse=reverse)
return im_masked
def save_im(self, output, format_out="GTiff"):
ds_out = save_map(self.array, output, gdal.GDT_UInt16, self.reference, out_no_data=self.out_no_data,
format_out=format_out)
if format_out == 'MEM':
return ds_out
This is the way I solved it using inheritance:
class Template:
def __init__(self):
self.array = None
self.reference = None
self.out_no_data = None
self.data_type = None
def mask(self, mask_aoi, mask_aoi_vl, replace_im=None, reverse=False):
map_mem = save_map(self.array, "", self.data_type, self.reference, format_out="MEM")
im_masked = MaskAOI(map_mem, mask_aoi, mask_aoi_vl, self.out_no_data,
replace_im=replace_im, reverse=reverse)
return im_masked
def save(self, output, format_out="GTiff"):
ds_out = save_map(self.array, output, self.data_type, self.reference, out_no_data=self.out_no_data,
format_out=format_out)
if format_out == 'MEM':
return ds_out
class MergeClasses(Template):
def __init__(self, input_data, m_classes, other_cls_val=None):
class_map1 = ReadMap(input_data)
self.reference = class_map1.reference
class_map1_array = class_map1.array
if class_map1.no_data is None:
self.out_no_data = 255
else:
self.out_no_data = class_map1.no_data
array_class = merge_cls(class_map1_array, m_classes, other_cls_val)
class_map_f = array_class.astype("int16")
self.array = class_map_f
self.data_type = gdal.GDT_UInt16

I want to write using the 'shelve' module, but after entering 3 data, I can't enter anymore and the keys in the file are stored incorrectly

I want to write using the 'shelve' module, but after entering 3 data, I can't enter anymore and the keys in the file are stored incorrectly ['3', '1', '2']. that's what happens on linux, and it's all good on windows
class BasicModel(ABC):
table = '.db'
def __init__(self):
self.id = None
self.created_date = None
self.updated_date = None
self.isValid = True
def save(self):
if self.isValid:
path = getAbsolutePath(self.table)
with shelve.open(path, writeback=True) as db:
# Shu obj yangi yaratilayotgani
if self.id is None:
self.created_date = datetime.now()
if list(db.keys()):
print(list(db.keys()))
self.id = int(list(db.keys())[-1]) + 1
else:
self.id = '1'
else:
self.updated_date = datetime.now()
db[str(self.id)] = self
else:
raise ValueError("Qiymatlardan biri noto'g'iri")
def delete(self):
with shelve.open(getAbsolutePath(self.table)) as db:
del db[str(self.id)]
def objects(table: str):
with shelve.open(getAbsolutePath(table)) as db:
for obj in db.values():
yield obj
#property
def isValid(self):
return self.__isValid
#isValid.setter
def isValid(self, value):
self.__isValid = value
class Brand(BasicModel):
table = 'Brands'
def __init__(self, name):
super().__init__()
self.name = name

Seeking advise on create a maze to solve with BFS in Python

Seeking advise on how structure python to create a maze, solve it with BFS and to have basic navigation within maze with number of moves required to navigate. Use move along the path, Up, Left, Right, Down. Below is some code that I mangled together to think about and figure how to structure python for this BFS algorithm code.
Is anyone open to mentoring on this BFS algorithm navigation maze python structure?
To basically follow the following algorithm:
function BREADTH-FIRST-SEARCH(problem) returns a solution node or failure
node ← NODE(problem.INITIAL)
if problem.IS-GOAL(node.STATE) then return node
frontier ← a FIFO queue, with node as an element
reached ← {problem.INITIAL}
while not IS-EMPTY(frontier ) do
node ← POP(frontier )
for each child in EXPAND(problem, node) do
s ← child.STATE
if problem.IS-GOAL(s) then return child
if s is not in reached then
add s to reached
add child to frontier
return failure
import sys
def parse_map(filename):
with open(filename, "r") as f:
return [[char for char in line] for line in f.read().rstrip("\n").split("\n")][3:]
def count_x(house_map):
return sum([ row.count('p') for row in house_map ] )
def printable_house_map(house_map):
return "\n".join(["".join(row) for row in house_map])
def add_x(house_map, row, col):
return house_map[0:row] + [house_map[row][0:col] + ['p',] + house_map[row][col+1:]] + house_map[row+1:]
def successors(house_map):
return [ add_x(house_map, r, c) for r in range(0, len(house_map)) for c in range(0,len(house_map[0])) if house_map[r][c] == '.' ]
def is_goal(house_map, k):
return count_x(house_map) == k
def bfs_graph_search(house_map):
fringe = [initial_house_map]
if house_map.goal_test(node.state):
return fringe
fringe = deque([house_map])
visited = set()
while fringe:
fringe = fringe.popleft()
visited.add(node.state)
for child in node.expand(problem):
if child.state not in fringe and child not in visited:
if house_map.goal_test(child.state):
return child
fringe.append(child)
return None
def solve(initial_house_map,k):
fringe = [initial_house_map]
while len(fringe) > 0:
for new_house_map in successors( fringe.pop() ):
if is_goal(new_house_map,k):
return(new_house_map,True)
fringe.append(new_house_map)
if __name__ == "__main__":
house_map=parse_map('map1.txt')
k = 2
print ("Initial ]house map:\n" + printable_house_map(house_map) + "\n\nSearching for solution...\n")
solution = solve(house_map,k)
print ("Found:")
print (printable_house_map(solution[0]) if solution[1] else "False")
class Agent:
def __init__(self, initial, goal=None):
self.initial = initial
self.goal = goal
def actions(self, state):
raise NotImplementedError
def result(self, state, action):
raise NotImplementedError
def goal_test(self, state):
if isinstance(self.goal, list):
return is_in(state, self.goal)
else:
return state == self.goal
def path_cost(self, c, state1, action, state2):
return c + 1
def value(self, state):
raise NotImplementedError
class FringeGraph:
def __init__(self, state, parent=None, action=None, path_cost=0):
self.state = state
self.parent = parent
self.action = action
self.path_cost = path_cost
self.depth = 0
if parent:
self.depth = parent.depth + 1
def path(self):
node, path_back = self, []
while node:
path_back.append(node)
node = node.parent
return list(reversed(path_back))
def solution(self):
return [node.action for node in self.path()[1:]]
def expand(self, agent):
return [self.child_node(agent, action)
for action in agent.actions(self.state)]
def child_node(self, agent, action):
next_state = agent.result(self.state, action)
next_node = Node(next_state, self, action, problem.path_cost(self.path_cost, self.state, action, next_state))
return next_node
class Agent:
def __init__(self, initial, goal=None):
self.initial = initial
self.goal = goal
def actions(self, state):
raise NotImplementedError
def result(self, state, action):
raise NotImplementedError
def goal_test(self, state):
if isinstance(self.goal, list):
return is_in(state, self.goal)
else:
return state == self.goal
def path_cost(self, c, state1, action, state2):
return c + 1
def value(self, state):
raise NotImplementedError
class FringeGraph:
def __init__(self, state, parent=None, action=None, path_cost=0):
self.state = state
self.parent = parent
self.action = action
self.path_cost = path_cost
self.depth = 0
if parent:
self.depth = parent.depth + 1
def path(self):
node, path_back = self, []
while node:
path_back.append(node)
node = node.parent
return list(reversed(path_back))
def solution(self):
return [node.action for node in self.path()[1:]]
def expand(self, agent):
return [self.child_node(agent, action)
for action in agent.actions(self.state)]
def child_node(self, agent, action):
next_state = agent.result(self.state, action)
next_node = Node(next_state, self, action, agent.path_cost(self.path_cost, self.state, action, next_state))
return next_node

Python Strategy Design Pattern

I apologize for my bad English.
I need your help. I just bring strategy design pattern, I have understood the pattern with a simple example, but the implementation in my project is very confusing for me, maybe you can help me.
I have for example these two classes:
from tkinter import *
from app.interface.settings import New_Font
from app.controller.interface_elements.button_controller import Button_controller
from app.controller.interface_elements.close_button_controller import Close_button_controller
class New_Button:
def __init__(self, insert_button_in_frame, text, width, position_X, position_Y, background_color, foreground_color, close_button_parameter):
self._number_types = {int, float}
self.set_frame (insert_button_in_frame)
self.set_text (text)
self.set_width (width)
self.set_position (position_X, position_Y)
self.set_color (background_color, foreground_color)
self.set_close_button_parameter (close_button_parameter)
if self.get_text() == 'Abbrechen':
self.controller = Close_button_controller(self.get_close_button_parameter())
else:
self.controller = Button_controller()
self.create_button ()
def create_button(self):
self.set_button(Button(self.get_frame(),
text=self.get_text(),
bg=self.get_background_color(),
fg=self.get_foreground_color(),
width=self.get_width(),
font=New_Font().get_defaultfont(),
command=lambda :self.controller.main_method()))
self.get_button().place(x=self.get_position_X(),
y=self.get_position_Y())
def set_button(self, button):
self._button = button
def get_button(self):
return self._button
def set_frame(self, insert_button_in_frame):
if type(insert_button_in_frame) == Frame:
self._frame = insert_button_in_frame
else: raise TypeError
def get_frame(self):
return self._frame
def set_text(self, text):
if type(text) == str:
self._text = text
else: raise TypeError()
def get_text(self):
return self._text
def set_width(self, width):
if type(width) in self._number_types:
self._width = width
else: raise TypeError
def get_width(self):
return self._width
def set_position(self, position_X , position_Y):
if type(position_X) in self._number_types and type(position_Y) in self._number_types:
self._position_X = position_X
self._position_Y = position_Y
else: raise TypeError
def get_position_X(self):
return self._position_X
def get_position_Y(self):
return self._position_Y
def set_color(self, background_color, foreground_color):
if type(background_color) == str and type(foreground_color) == str:
self._background_color = background_color
self._foreground_color = foreground_color
else: raise TypeError
def get_background_color(self):
return self._background_color
def get_foreground_color(self):
return self._foreground_color
def set_controller(self, controller):
self._controller = controller
def get_controller(self):
return self._controller
def set_info(self, search_for):
self._info = self.get_button().cget(search_for)
def get_info(self):
return self._info
def set_close_button_parameter(self, close_button_parameter):
self._close_button_parameter = close_button_parameter
def get_close_button_parameter(self):
return self._close_button_parameter
and
from app.gui.top_frame import *
from app.interface.settings import New_Font
from app.controller.interface_elements.radiobutton_controller import Radiobutton_controller
class New_Radiobutton:
def __init__(self, frame_to_insert_radiobutton, radiobutton_label, button_horizontal_position, button_vertical_position, radiobutton_group, radiobutton_value, crawled_radiobuttons):
self._number_types = {int, float}
self._allowed_group_types = {int, float, str}
self._values = {1,3,5}
self._disable = {3,4,5,6}
self.set_frame_to_insert_radiobutton (frame_to_insert_radiobutton)
self.set_radiobutton_label (radiobutton_label)
self.set_position (button_horizontal_position, button_vertical_position)
self.set_radiobutton_group (radiobutton_group)
self.set_radiobutton_value (radiobutton_value)
self.create_radiobutton()
self._radiobutton_controller = Radiobutton_controller(crawled_radiobuttons)
self.set_first_radiobutton_of_a_group()
def create_radiobutton(self):
self.set_radiobutton(Radiobutton(self.get_frame_to_insert_radiobutton(),
text=self.get_radiobutton_label(),
variable=self.get_radiobutton_group(),
value=self.get_radiobutton_value(),
font=New_Font().get_defaultfont(),
command= lambda : self._radiobutton_controller.main_method()))
self.get_radiobutton().place(x=self.get_button_horizontal_position(),
y=self.get_button_vertical_position())
def set_first_radiobutton_of_a_group(self):
if self.get_radiobutton_value() in self._values:
self.get_radiobutton().invoke()
if self.get_radiobutton_value() in self._disable:
self.get_radiobutton().config(state=DISABLED)
def get_frame_to_insert_radiobutton(self):
return self._frame_to_insert_radiobutton
def set_frame_to_insert_radiobutton(self, frame_to_insert_radiobutton):
if type(frame_to_insert_radiobutton) == tkinter.Frame:
self._frame_to_insert_radiobutton = frame_to_insert_radiobutton
else: raise TypeError(frame_to_insert_radiobutton +
' frame_to_insert_radiobutton i not from type tkinter.Frame')
def get_radiobutton_label(self):
return self._radiobutton_label
def set_radiobutton_label(self, radiobutton_label):
if type(radiobutton_label) == str:
self._radiobutton_label = radiobutton_label
else: raise TypeError(radiobutton_label +
' radiobutton_label is not from type string')
def get_button_horizontal_position(self):
return self._button_horizontal_position
def get_button_vertical_position(self):
return self._button_vertical_position
def set_position(self, button_horizontal_position, button_vertical_position):
if type(button_horizontal_position) and type(button_vertical_position) in self._number_types:
self._button_horizontal_position = button_horizontal_position
self._button_vertical_position = button_vertical_position
else: raise TypeError(button_horizontal_position + ' ' + button_vertical_position +
' button_horizontal_position or button_vertical_position or both is/are not from type number')
def get_radiobutton_group(self):
return self._radiobutton_group
def set_radiobutton_group(self, radiobutton_group):
if type(radiobutton_group) in self._allowed_group_types:
self._radiobutton_group = radiobutton_group
else: raise TypeError(radiobutton_group +
' radiobutton_group is not from type int/float or string')
def get_radiobutton_value(self):
return self._radiobutton_value
def set_radiobutton_value(self, radiobutton_value):
if type(radiobutton_value) in self._number_types:
self._radiobutton_value = radiobutton_value
else: raise TypeError(radiobutton_value +
'radiobutton_value is not from type number')
def get_radiobutton_controller(self, radiobutton_controller):
return self.get_radiobutton().cget(radiobutton_controller)
def set_radiobutton(self, radiobutton):
self._radiobutton = radiobutton
def get_radiobutton(self):
return self._radiobutton
both classes need 90% the same methods and I have 2 other methods where it is. how do I start encapsulating the changeable now? because the button, no matter if radio, checkbox or button, is only created with the create method
thank you for your help

Python Binary Tree

I'm working on a binary tree in Python3 and so far almost everything has been working like expected; however, I have a function that is supposed to return a list of all children for any given node and for whatever reason I'm only getting a list of the object addresses, and not calling my overridden __str__(self) method.
from collections import deque # http://docs.python.org/3.1/tutorial/datastructures.html
class BinaryNode: # binary tree functionality via iterative means
def __init__(self, name, data):
self.Left = None
self.Right = None
self.Parent = None
self.Name = name
self.Data = data
return
def AddNew(self, name, data):
q = []
q.append(self)
while q:
i = q.pop()
if i.Name == name:
i.Data = data
return i
elif name < i.Name:
if i.Left:
q.append(i.Left)
else:
i.Left = BinaryNode(name, data)
i.Left.Parent = i
return i.Left
else:
if i.Right:
q.append(i.Right)
else:
i.Right = BinaryNode(name, data)
i.Right.Parent = i
return i.Right
def Find(self, name):
q = deque()
q.append(self)
'''if self.Left: q.append(self.Left)
if self.Right: q.append(self.Right)'''
while q:
i = q.pop()
print(i)
if i.Name == name:
return i
elif name < i.Name:
if i.Left: q.append(i.Left)
else: return None
else:
if i.Right: q.append(i.Left)
else: return None
def Children(self):
children = []
q = deque()
if self.Left: q.append(self.Left)
if self.Right: q.append(self.Right)
while q:
i = q.popleft()
if i.Left: q.append(i.Left)
if i.Right: q.append(i.Right)
children.append(i)
return children
def Parents(self):
lst = []
i = self.Parent
while i is not None:
lst.append(i)
i = i.Parent
return lst
def __str__(self): return "{} : {}".format(self.Name, self.Data)
and I'm testing it by calling
test = BinaryNode("Jesse", 21)
print(test)
print(test.AddNew("David", 22))
print(test.AddNew("Marli", 23))
print(str(test.Children()))
print(test.Find("David"))
print(test.Find("David").Children())
print(test.Find("Gary")) #Will return None
with the resulting console output
Jesse : 21
David : 22
Marli : 23
[<__main__.BinaryNode object at 0x000000000333E160>, <__main__.BinaryNode object at 0x000000000333E1D0>, <__main__.BinaryNode object at 0x000000000333E198>]
David : 22
[<__main__.BinaryNode object at 0x000000000333E1D0>]
None
UPDATE:
Here is the answer I implemented:
def __repr__ (self): return str(self)
Python containers always use the representation of contained objects.
Implement a __repr__ method too and that'll be used when printing the list; you can make it an alias for __str__ if you wish:
__repr__ = __str__
or explicitly print each element in your list:
print(', '.join(map(str, test.Children())))

Resources