Python自定义myPassword类仅能运行一次的问题排查求助
myPassword Class Only Works Once Hey there! Let's break down why your password generation class only produces a single unique password, no matter how many times you use it.
The Root Cause
Looking at your code, all the password generation logic is written directly as class-level attributes (like passw = random.sample(...)). Here's the key thing: Python evaluates class-level code once, when the class is first defined—not when you create instances of the class. That means all the random choices and string concatenation run one time when your script loads, and every instance of myPassword will reuse that pre-generated passw value forever after.
The Fix: Move Logic to __init__
To generate a new password every time you create a myPassword instance, you need to move the password generation code into the class's __init__ method. This method runs every time you create a new instance, so it'll generate a fresh random password each time.
Here's the corrected, complete version of your class:
import csv import random class myPassword: # Keep fixed character sets as class attributes (they don't change) azlower = "abcdefghijklmnopqrstuvwxyz" azupper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" vowel = "aeiouAEIOU" simbol = "!@#$%*" # Keeping your spelling here, though it's usually "symbol" def __init__(self): # Generate password fresh every time an instance is created self.passw = ''.join(map(str, random.sample(range(9), 2))) self.passw += random.choice(self.simbol) self.passw += random.choice(self.azupper) self.passw += random.choice(self.vowel) self.passw += random.choice(self.azlower) self.passw += random.choice(self.simbol) # Finish the truncated part from your original code self.passw += ''.join(map(str, random.sample(range(9), 3)))
How to Use It
Now, every time you create a new instance, you'll get a unique password:
# First instance: generates a new password pw1 = myPassword() print(pw1.passw) # Second instance: generates an entirely new password pw2 = myPassword() print(pw2.passw)
Bonus Tip: Add a Re-Generate Method
If you want to generate a new password for an existing instance without creating a new one, you can refactor the logic into a reusable method:
class myPassword: # ... existing class attributes ... def __init__(self): self.generate_password() def generate_password(self): self.passw = ''.join(map(str, random.sample(range(9), 2))) self.passw += random.choice(self.simbol) self.passw += random.choice(self.azupper) self.passw += random.choice(self.vowel) self.passw += random.choice(self.azlower) self.passw += random.choice(self.simbol) self.passw += ''.join(map(str, random.sample(range(9), 3)))
Now you can call pw1.generate_password() to refresh the password for the same instance whenever you need.
内容的提问来源于stack exchange,提问作者king sway

