首页 新闻 会员 周边

Python运行这段代码出现can't set attribute是什么问题?

0
[已解决问题] 解决于 2019-08-15 17:30

class Test2Class():
def init(self,name):
self.__name=name
#装饰器
@property
def gettest1(self):
return self.__name

@gettest1.setter
def   settest1(self,name):
    self.__name=    name

@property
def onlytest(self):
    return  time.time()

test2clas= Test2Class("w")
test2clas.gettest1 # 读取
print(test2clas.gettest1 )
test2clas.gettest1='wwwwee'

times=test2clas.onlytest # 读取

print(str(times))

永远跟党走i的主页 永远跟党走i | 小虾三级 | 园豆:1519
提问于:2019-08-15 14:09
< >
分享
最佳答案
2
import time

class Test2Class(object):
    def __init__(self, name):
        self.__name=name

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, name):
        self.__name = name

    @property
    def now(self):
        return time.time()

if __name__ ==  "__main__":
    test2clas= Test2Class("w")
    print(test2clas.name)

    test2clas.name = 'wwwwee'
    print(test2clas.name)

    times = test2clas.now # 读取
    print(str(times))

Your code is like shit

奖励园豆:5
会长 | 专家六级 |园豆:12401 | 2019-08-15 14:36

太狠了。。。。

永远跟党走i | 园豆:1519 (小虾三级) | 2019-08-15 16:05

@Cgrain:

  • 你的init方法名不对
  • 代码也没有格式化,看起来乱七八糟
  • 既然定义成了属性,这么还用get和set做前缀
会长 | 园豆:12401 (专家六级) | 2019-08-15 16:08

@会长: 原本的代码是这样的,上传的时候没注意到样式

原本的代码是这样的,然后看到了装饰器,于是也类似这样写:

刚刚我实验了一下,发现了问题的所在,您看一下是不是这样的:

如果需要用到装饰器,就必须要统一方法名,对吗?

永远跟党走i | 园豆:1519 (小虾三级) | 2019-08-15 16:58

以后实践代码好好写了,/(ㄒoㄒ)/~~

永远跟党走i | 园豆:1519 (小虾三级) | 2019-08-15 17:00

@Cgrain: 应该这样调用:

test2class.settest1 = 'werwrw' # 这个才是set方法,你调用了get方法,当然错了

不是必须统一方法名,而是这样能方便代码调用者方便理解代码。

obj.name = 'hello'
print(obj.name)

是不是比写成下面这样好读:

obj.setname = 'hello'
print(obj.getname)

与其这样,还不如不加装饰器,直接:

obj.setname('hello')
print(obj.getname())

普通方法用动词,加了装饰器就当做属性用了,属性应该是个名词吧。

不用说“您”,我也是小弟而已

会长 | 园豆:12401 (专家六级) | 2019-08-15 17:08

@会长: 好的,懂了

永远跟党走i | 园豆:1519 (小虾三级) | 2019-08-15 17:29
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册