【问题标题】:Python strange attributePython 奇怪的属性
【发布时间】:2018-09-30 04:56:51
【问题描述】:

我一直在学习 Python 3 在线课程,并进行了练习。 你应该编写一个名为 Foo 的类,它有一个名为 x 的属性,它是根据以下规则设置的:

  • 创建Foo类时x的初始值为0。 用数字设置 x 时: 如果该数为非负数,则将其右侧的两位数存储在 x 中。

    p=Foo()

    print(p.x) -----> 输出:0

    p.x=123

    print(p.x) -----> 输出:23

我只是想知道 x 是如何通过对象获得分配的。

>>> p=Foo()
>>> p.x = 1234
>>> p.x == 34
True
>>> type(p.x)
<class 'int'>

【问题讨论】:

  • 阅读属性,例如here

标签: python class oop attributes


【解决方案1】:
class Foo():
def __init__(self):
    self.n=0
@property
def x(self):
    return self.n
@x.setter
def x(self, num):

    if num<100 and num>=0:
        self.n=num
    elif num>100 and num%100!=0 :
        self.n=num%100
    elif num<0:
        self.n=-1
    else:
        self.n=0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 2012-12-17
    • 2017-04-10
    • 1970-01-01
    相关资源
    最近更新 更多