weixin_42621164
沙德沃克
采纳率100%
2020-07-17 00:19 阅读 58

麻烦大佬看下为啥调用实例类密码函数无法用property

5

class user:
def init(self,name='abcdefg',password='1234567'):
#双下划线开头,隐藏变量
self.__name=name
self.__password=password

def getname(self):
    return self.__name;
def setname(self,name):
    if isinstance(name,str) and 4<= len(name) <=8:
        self.__name = name
    else:
        print("无效用户名")
name=property(fget=getname,fset=setname);

@property
def getpwd(self):
    return self.__password;
@getpwd.setter
def setpwd(self,password):
    if isinstance(password,str) and 4 <= len(password) <= 8:
        self.__password = password
    else:
        print("无效密码")
# password = property(fget=getpwd, fset=setpwd);

c=user()
c.name='a'
c.password='1'

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    acdefghb 水滴重甲 2020-07-17 13:49

    property 用错了
    修改为我下面的这种

    
    class user:
        def init(self, name='abcdefg', password='1234567'):
            # 双下划线开头,隐藏变量
            self.__name = name
            self.__password = password
    
        def getname(self):
            return self.__name
    
        def setname(self, name):
            if isinstance(name,str) and 4<= len(name) <= 8:
                self.__name = name
                print("用户名设置成功")
            else:
                print("无效用户名")
    
        name = property(fget=getname, fset=setname)
    
        @property
        def password(self):
            """I'm the 'password' property."""
            return self.__password
    
        @password.setter
        def password(self, password):
            if isinstance(password, str) and 4 <= len(password) <= 8:
                self.__password = password
                print("密码设置成功")
            else:
                print("无效密码")
    
    c = user()
    c.name = 'abcde'
    c.password = '12345'
    
    
    点赞 1 评论 复制链接分享

相关推荐