Java中使用Setter/Getter跨类访问变量问题求助
解决SendMail类无法从Users类获取密码的问题
嘿,我碰到过好几个类似的场景,大概率是下面几个常见坑导致的,咱们一个个排查解决:
1. 实例不共享:用了两个不同的Users对象
这是最常见的问题!如果你在设置密码的时候用了一个Users实例,但是在SendMail里又新建了一个全新的Users实例,那后者的密码肯定是空的——因为两个实例完全独立。
举个错误的例子:
class Users: def __init__(self): self.password = None def setpassword(self, pwd): self.password = pwd def getpassword(self): return self.password class SendMail: def send(self): # 这里新建了一个未设置密码的Users实例 user = Users() print("要发送的密码:", user.getpassword()) # 输出None # 主逻辑 user = Users() user.setpassword("MySecurePwd123") mailer = SendMail() mailer.send()
改成正确的写法,把已经设置好密码的Users实例传给SendMail:
class SendMail: # 初始化时接收已有的Users实例 def __init__(self, user_instance): self.user = user_instance def send(self): print("要发送的密码:", self.user.getpassword()) # 输出MySecurePwd123 # 主逻辑 user = Users() user.setpassword("MySecurePwd123") mailer = SendMail(user) # 传入已设置密码的实例 mailer.send()
2. 密码变量的作用域错了
如果Users类里的setpassword方法把密码存在了局部变量里,而不是实例的属性(self.password),那getpassword根本拿不到这个值。
错误示例:
class Users: def setpassword(self, pwd): password = pwd # 这是方法内的局部变量,方法结束就销毁了 def getpassword(self): return password # 这里会报错或者返回空
正确写法,把密码绑定到实例上:
class Users: def __init__(self): self.password = None # 先初始化实例属性 def setpassword(self, pwd): self.password = pwd # 赋值给实例属性 def getpassword(self): return self.password
3. getpassword方法的访问权限被限制了
如果你的Users类把getpassword定义成了私有方法(比如Python里用__getpassword,Java里用private),那SendMail类根本无权调用这个方法,自然拿不到密码。
比如错误的私有方法写法:
class Users: def __init__(self): self.password = None def setpassword(self, pwd): self.password = pwd # 双下划线开头是私有方法 def __getpassword(self): return self.password
改成公共方法(去掉双下划线):
class Users: def __init__(self): self.password = None def setpassword(self, pwd): self.password = pwd # 公共方法,外部可以访问 def getpassword(self): return self.password
4. 异步场景下的时序问题
如果setpassword是异步操作(比如从数据库/API拉取密码后设置),而SendMail在密码还没设置完成时就调用了getpassword,那也会拿到空值。
比如Python的异步错误示例:
import asyncio class Users: def __init__(self): self.password = None async def setpassword(self): # 模拟异步获取密码 await asyncio.sleep(1) self.password = "AsyncPwd456" def getpassword(self): return self.password class SendMail: def __init__(self, user): self.user = user def send(self): print("异步场景下的密码:", self.user.getpassword()) # 输出None async def main(): user = Users() # 这里直接调用send,没等setpassword完成 mailer = SendMail(user) mailer.send() await user.setpassword() asyncio.run(main())
正确写法,等待异步操作完成后再调用SendMail:
async def main(): user = Users() await user.setpassword() # 先等密码设置完成 mailer = SendMail(user) mailer.send() # 输出AsyncPwd456 asyncio.run(main())
你可以对照自己的代码,看看是哪个环节出了问题,应该就能解决啦!
内容的提问来源于stack exchange,提问作者Klayd Pro
相关产品推荐
相关产品推荐

