How do i Clone an object?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Fuugie
    New Member
    • Sep 2010
    • 32

    How do i Clone an object?

    I am having trouble trying to clone a tree i made. Any suggestions?

    My Input:
    Code:
    from cs1graphics import *
    
    paper = Canvas(300, 200, 'skyBlue', 'My Forest')
    
    grass = Rectangle(300, 80, Point(150,160))
    grass.setFillColor('green')
    grass.setBorderColor('green')
    grass.setDepth(75)                
    paper.add(grass)
    
    tree1 = ('tree', 'tree_bottom', 'tree_base')
    tree = Polygon(Point(50,80), Point(30,125), Point(70,125))
    tree.setFillColor('darkGreen')
    paper.add(tree)
    
    tree_bottom = Polygon(Point(50,80), Point(30,150), Point(70,150))
    tree_bottom.setFillColor('darkGreen')
    paper.add(tree_bottom)
    
    tree_base = Polygon(Point(50,150), Point(45,165), Point(55,165))
    tree_base.setFillColor('brown')
    paper.add(tree_base)
    
    tree2 = tree1.clone()
    tree2.move(170,30)
    tree2.scale(1.2)
    paper.add(tree2)
    Error:
    Code:
    Traceback (most recent call last):
      File "C:/Users/Robert/Documents/CSIS Projects/Ex3_8.py", line 30, in <module>
        tree2 = tree1.clone()
    AttributeError: 'tuple' object has no attribute 'clone'
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    I can see how you got the error. This will not work, because a tuple object has no method named clone:
    Code:
    tree1 = ('tree', 'tree_bottom', 'tree_base')
    tree2 = tree1.clone()
    What is tree2 supposed to be?

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      "clone" is too vague. You have at least 2 options with a tuple/list
      tree2 = tree1
      creates a reference to tree1, i.e. they both point to the same block of memory, so if you change one, you change both. For a copy, you have to convert to a list.
      Code:
      import copy
      tree1 = ('tree', 'tree_bottom', 'tree_base')
      tree2 = tree1
      print tree2
      print id(tree2), id(tree1)   ## they are the same
      
      tree3 = copy.copy(list(tree1))   ## shallow copy (look it up)
      print tree3
      print id(tree3), id(tree1)   ## they are different

      Comment

      Working...