simple class question

Discussion in 'Python' started by C GIllespie, Jan 20, 2004.

  1. C GIllespie

    C GIllespie Guest

    Dear all,

    I'm new to both python and OOP, so could I ask a simple question.

    I have class:

    class species:
    __init__(self,pop=0):
    self.pop=pop

    Now I want to do something like this:

    X=species(pop=10)
    Y=species(pop=X.pop)
    OK, but now I want to update X.pop and have that mirrored in Y.pop, i.e. if
    X.pop=5, Y.pop now equals 5.

    What is the best/nicest/simplest way of doing this?

    Many thanks

    Colin
     
    C GIllespie, Jan 20, 2004
    #1
    1. Advertisements

  2. C GIllespie

    Matt Grayson Guest

    Instead of declaring Y as a new instance of species, just set Y equal
    to X:

    x = species(pop=10)
    y = x
    x.pop = 15
    print y.pop
     
    Matt Grayson, Jan 20, 2004
    #2
    1. Advertisements

  3. C GIllespie

    anton muhin Guest

    In some cases pop should be class attribute.

    regards,
    anton.
     
    anton muhin, Jan 20, 2004
    #3
  4. Example using class attribute:
    .... pop = [0] #Must be mutable object
    .... def __init__(self, pop = 0):
    .... self.pop[0] = pop
    ....
     
    Michael Spencer, Jan 20, 2004
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.