Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
64 views
in Technique[技术] by (71.8m points)

python - Passing object into class method dynamically

I am trying to pass in an object so that it will be modified by the method defined infection. However, when I do pass it in, as I show below, it only does it once. This is my first experience making dynamic objects, so I'm not quite sure how to get it to keep going.

class Region:
    def __init__(self, name, population, cases, deaths):
        self.name = name
        self.population = population
        self.cases = cases
        self.deaths = deaths
        print(name, cases)       

    def infection(self, name, population, cases):
        while population > cases:
            cases = cases + 1
            return (cases)        
    
westernEurope = Region("Western Europe", 1000000, 0, 0)
print(westernEurope.infection("Western Europe", 1000000, 0))

What I want to happen is that the infection method should keep incrementing until it reaches the number of cases, but I also need to be able to print each incrementation. Any help is much appreciated.

question from:https://stackoverflow.com/questions/65870696/passing-object-into-class-method-dynamically

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have an indentation problem with your code.

This should work for your requirement:

class Region:
    def __init__(self, name, population, cases, deaths):
        self.name = name
        self.population = population
        self.cases = cases
        self.deaths = deaths
        print(name, cases)       

    def infection(self, name, population, cases):
        while population > cases:
            cases = cases + 1
            print(cases)
        return (cases)        
    
westernEurope = Region("Western Europe", 1000000, 0, 0)
print(westernEurope.infection("Western Europe", 1000000, 0))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...