简体   繁体   中英

how to call a the class from a method within the class in python to redefine a variable?

I'm having some issues redefining an object that I created by using a method within the same class that defines such object. I have written a small python example. Here I'm trying to create an object called dog3 using a method in the class dog that calls itself in order to change its dog3.getDogName. When I print the dog3 name, the call to init did not took effect. Does anyone knows how to perform this operation?

I expect to get an output as

woofy max bear

but instead of bear I get woofy again.

import sys


class Dog():
    def __init__(self, name = 'woofy'):
        self.name = name

    def getDogName(self):
        return self.name

    def newDog(self, new_name):
        return Dog(new_name)


class Animals():
    def __init__(self, *args):

        dog1 = Dog()
        print(dog1.getDogName())

        dog2 = Dog('max')
        print(dog2.getDogName())

        dog3 = dog1
        dog3.newDog('bear')
        print(dog3.getDogName())


def mainApp(args):
    global app 
    app = Animals(args)

if __name__ == "__main__":
    mainApp(sys.argv)

I'm sure an experience python programer would know how to do an operation like this.

Thank you for your help in advance.

Your code have defined the method newDog to return a new instance of Dog .

Your code also have dog3 being assigned an instance of Dog , but when your code called dog3.newDog(...) the return value is not assigned to anything. so the new Dog instance that got created went nowhere.

You might want to consider doing this instead.

    dog3 = dog1.newDog('bear')
    print(dog3.getDogName())

newDog is creating a new dog and not modifying the old one

If you want newDog to return a new dog, then do this:

dog3 = dog1.newDog("bear")

or really you should just be doing

dog3 = Dog("bear")

If you want newDog to modify the current Dog instance, do this:

def renameDog(self, new_name):
    self.name = new_name

Don't make instance constructors unless you want to clone certain parameters. It can get confusing.

The method NewDog "return" a new Dog instance, but it will not change what it is, so if u want to change the name of current Dog instance, do this:

class Dog():
    def change_name(self, new_name):
        self.name = new_name

if u want to get another Dog instance, do this:

class Dog(object):
  @staticmethod
  def new_dog(new_name):
      return Dog(new_name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM