简体   繁体   English

Python 面向对象编程(OOP)问题

[英]Python Object-oriented programming (OOP) question

class User:
 def __init__(self,user_id, username):
    self.id=user_id
    self.username=username
    self.followers=0
    self.following=0
 def follow(self,user):
   user.followers +=1
   self.following +=1

user_1=User("001","jack")
user_2=User("002","luck")

user_1.follow(user_2)    
print(user_1.followers)
print(user_1.following)

why is the answer 0 and 1 when I print (user_1.followers) and print(user_2.following).为什么当我打印(user_1.followers)和打印(user_2.following)时答案是 0 和 1。 I can't tell from where is pulling the value, is it from the constructor or method.我不知道从哪里提取值,是来自构造函数还是方法。 Thanks谢谢

In your example above, user_1 follows user_2.在上面的示例中,user_1 跟随 user_2。 Therefore, user_1 has NO followers (yet) but IS following user_2.因此,user_1 没有关注者(还),但正在关注 user_2。 Hence the output:因此 output:

print(user_1.followers) # 0
print(user_1.following) # 1

Hope this helps...希望这可以帮助...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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