如何在另一个对象中实例化一个对象,然后从第二个对象调用方法(python)

时间:2015-08-29 18:03:18

标签: object python-3.x data-structures linked-list

我有以下代码:

类提交:

id = 0
commits = []

def __init__(self, message=None, changes=None):
    Commit.id += 1
    self.id = Commit.id
    self.message = tuple([message])
    self.changes = tuple(changes)
    Commit.commits.append(self.message + self.changes)
    self.commits = Commit.commits
    self.next = None

班级分支:

def __init__(self):
    self.tail = None
    self.head = None

def new_commit(self, commit):
    if not self.head:
        self.head = commit
        self.tail = self.head
    else:
        self.tail.next = commit
        self.tail = self.tail.next

类存储库:

branches = {}

def __init__(self, name):
    self.name = name
    self.branches = Repository.branches
def branch(self, branch_name):
    self.branch_name = Branch()
    self.branches[branch_name] = self.branch_name
    return self.branches[branch_name]

但是当我这样做来实例化它时:

    repo = Repository("syllabus 2.0")
    repo.branch("master").new_commit(Commit(message="add readme", changes=[("CREATE", "README.md")]))
    print(repo.branch("master").head)

它打印无 为什么会这样?

1 个答案:

答案 0 :(得分:0)

从不介意用

修复它
def branch(self, branch_name):
    if branch_name not in self.branches:
        self.branches[branch_name] = Branch()
        return self.branches[branch_name]
    else:
        return self.branches[branch_name]