鱼C论坛

 找回密码
 立即注册
查看: 1568|回复: 3

[已解决]类中的的递增

[复制链接]
发表于 2017-11-21 14:04:14 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
class User():
    def __init__(self,first_name,last_name,age,height):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age
        self.height = height
        self.login_attempts = 0

    def describe_user(self):
        
        name = ("name=" + self.first_name + self.last_name + "\nage=" + str(self.age) + "\nheight=" + str(self.height) + "cm")

        return name.title()

    def greet_user(self):
        print(self.first_name + self.last_name + "Hello!")


    def increment_login_attempts(self,one):
        self.login_attempts += 1

    def reset_login_attempts(self,zero):
        self.login_attempts = zero
        
    def print_login_attempts(self):
        print("Attempt number " + str(self.login_attempts))
        
Family_user = User("sun","shan",25,183)
Family_user.increment_login_attempts()
Family_user.print_login_attempts()
      
Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\110.py", line 29, in <module>
    Family_user.increment_login_attempts()
TypeError: increment_login_attempts() missing 1 required positional argument: 'one'

问题:我想递增加1  这里不懂怎么操作了
最佳答案
2017-11-21 14:43:20
pythonwei 发表于 2017-11-21 14:33
def increment_login_attempts(self,one):
        self.login_attempts += one

你是想要一个和具体实例化无关的计算变量吗?
可以将这个函数声明为@staticmethod 或者 @classmethod
然后直接用类名调用即可

详细你可以百度一下
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-11-21 14:22:30 | 显示全部楼层
你的这个方法
def increment_login_attempts(self,one):
        self.login_attempts += 1
形参中有个one是干什么的?
实际调用的时候并没有写这个参数
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-11-21 14:33:39 | 显示全部楼层
BngThea 发表于 2017-11-21 14:22
你的这个方法
def increment_login_attempts(self,one):
        self.login_attempts += 1

def increment_login_attempts(self,one):
        self.login_attempts += one

如何用这个方法给属性login_attempts的值固定加1?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-11-21 14:43:20 | 显示全部楼层    本楼为最佳答案   
pythonwei 发表于 2017-11-21 14:33
def increment_login_attempts(self,one):
        self.login_attempts += one

你是想要一个和具体实例化无关的计算变量吗?
可以将这个函数声明为@staticmethod 或者 @classmethod
然后直接用类名调用即可

详细你可以百度一下
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-13 03:07

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表