2015-06-09 2 views
1

Это будет легче для меня, чтобы объяснить проблему после того, как вы видите код:изменения аргументов, прежде чем отправить работать, питона 2,7

первый класс:

class Circuit: 
"""creation of a circuit of nodes""" 
def __init__ (self): 
    self.nodes=dict() 
    self.inputs=dict() 
    self.outputs=dict() 

def add_node_to_circuit(self,x): 
    if not isinstance(x, Node): 
     raise TypeError('Node expected') 

    if not self.nodes.has_key(x): 
     self.nodes[x]=None 
    else : print "Node already exist .error in add node to circuit because user not allowed changing nodes in circuit after they created" 

второй класс:

class Node: 
def __init__ (self): 
    """equals to default constuctor in c + setting the variables 
    do not read this constructor directly""" 
    self.name=[] 
    self.input_one=[] 
    self.input_two=[] 
    self.output=[] 
    self.action=[] 
    self.size=0 
    ##print "constructor has been read" self checking 
    ##print "constructor self= " ,self 
    ##print " with :",name,input_one,input_two,output,action 

def read_from_line_anygate(self,line): 
    if isinstance(line,list)==False : print "error with line not being a list,anygate" 
    self.name=line[0] 
    self.input_one=line[1] 
    self.input_two=line[2] 
    self.output=line[3] 
    self.action=line[4] 
    self.size=5 
def insert_Node(self,line): 
    """line needs to be a list type""" 
    if len(line)==5 : self.read_from_line_anygate(line) 
    elif len(line)==4 : self.read_from_line_gatenot(line) 
    else : print "error in insert_Node" 

главная:

w=Circuit() 

g = open("cir1.gatelevel","r") 
x=Node() 
for l in g: 
    x.insert_Node(l.strip().split()) 
    w.add_node_to_circuit(x) 

##print "read gate level file done" self checking 
g.close() 

Как вы могли видеть, у меня есть некоторые другие методы, но они очень интуитивно понятны, за исключением того, что я получил также str и . для класса Node. Моя проблема в том, что в основном, за исключением 1-й итерации, всякий раз, когда x меняет изменения w.nodes на нее, даже если строка w.add_node_to_circuit была прочитана, проверена с помощью отладчика и, кроме того, она удаляет последний ключ, который был в узлы словаря вместо их добавления к ним существуют. Также я пытаюсь напечатать в основных w.nodes, w.input, w.output это то, что я получаю:

Node already exist .error in add node to circuit because user not allowed changing nodes in circuit after they created 
Node already exist .error in add node to circuit because user not allowed changing nodes in circuit after they created 
Node already exist .error in add node to circuit because user not allowed changing nodes in circuit after they created 
Node already exist .error in add node to circuit because user not allowed changing nodes in circuit after they created 
Node already exist .error in add node to circuit because user not allowed changing nodes in circuit after they created 
Node already exist .error in add node to circuit because user not allowed changing nodes in circuit after they created 
Node already exist .error in add node to circuit because user not allowed  changing nodes in circuit after they created 
Node already exist .error in add node to circuit because user not allowed    changing nodes in circuit after they created 
{['X_c2_d3', '_c2_net3', 'inp3', '_net3', 'NAND']: None} 
{'inp1': None, 'inp3': None, 'inp2': None} 
{'outp': None, '_outp2': None, '_outp3': None}  

Я использую Python 2.7.

+0

Почему 'Node' есть' метод insert_Node'? И почему вы продолжаете пытаться добавить узел 'x' в' w'? – user2357112

+0

Что касается первой части вопроса, я пытаюсь построить ее несколько как граф или дерево или лес (в конце концов я хочу, чтобы он разрешил мне схему логических ворот). Я согласен, что имя insert_Node не самое лучшее, но какие у меня есть другие варианты? сделать это в init? Для второй части я хотел получить в конце 3 словаря, один для ввода один для вывода и один, который будет содержать все узлы в моей схеме. Я все еще не понял все, но следующий шаг оттуда будет создан еще один класс, провод, который свяжет узлы от одного к другому. – maor

ответ

3

Вы не создаете новые узлы в основном, а изменяете x каждый раз. Поскольку он передается как ссылка, он всегда один и тот же. Чтобы избежать этого, вам нужно будет создать x внутри цикла:

w=Circuit() 

g = open("cir1.gatelevel","r") 
    for l in g: 
     x=Node() 
     x.insert_Node(l.strip().split()) 
     w.add_node_to_circuit(x) 
+0

У вас это есть, теперь оно работает, спасибо. Я также получил следующий вопрос: в C/C++ я сразу вижу, если аргумент отправляется по значению или указателю или ссылке. Как я могу увидеть разницу между ними в python? – maor

+0

@maor в Python * все * передается по ссылке. Если это непреложный объект, вы никогда не увидите никаких побочных эффектов, но если он изменен, вам нужно быть осторожным либо не изменять его, либо делать копию. –

+0

@maor: Если вы привыкли к семантике переменных C++, вы можете найти следующую статью полезной: https://rg03.wordpress.com/2007/04/21/semantics-of-python-variable-names-from- ac-perspective/ – user2357112

Смежные вопросы