相关疑难解决方法(0)

如何在__init__中设置python属性

我有一个具有属性的类,我希望将其转换为属性,但此属性设置在其中__init__.不知道应该怎么做.没有设置这个属性__init__很容易,效果很好

import datetime

class STransaction(object):
    """A statement transaction"""
    def __init__(self):
        self._date = None

    @property
    def date(self):
        return self._date

    @date.setter
    def date(self, value):
        d = datetime.datetime.strptime(value, "%d-%b-%y")
        self._date = d

st = STransaction()
st.date = "20-Jan-10"
Run Code Online (Sandbox Code Playgroud)

但是一旦初始化需要发生,__init__它会变得更复杂,我不确定正确的行动方案.

class STransaction(object):
    """A statement transaction"""
    def __init__(self, date):
        self._date = None
Run Code Online (Sandbox Code Playgroud)

奇怪的是,以下似乎工作但闻起来非常糟糕.

class STransaction(object):
    """A statement transaction"""
    def __init__(self, date):
        self._date = None
        self.date = date

    @property
    def date(self):
        return self._date

    @date.setter
    def date(self, value):
        d = datetime.datetime.strptime(value, …
Run Code Online (Sandbox Code Playgroud)

python properties

24
推荐指数
2
解决办法
2万
查看次数

Python没有在类中显示print语句的结果

这可能是微不足道的,但在搜索时我没有得到解决方案:

我有以下简单的类:

class Celcius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature*1.8) + 32

    def get_temperature(self):
        print "getting temp"
        return self._temperature

    def set_temperature(self, value):
        if value < -273:
            raise ValueError("dayum u trippin' fool")
        print "setting temp"
        self._temperature = value

    temperature = property(get_temperature, set_temperature)

c = Celcius()
Run Code Online (Sandbox Code Playgroud)

当我在Sublime Text 3(通过点击cmd + B)中运行它时,控制台不会打印任何内容.我应该看到:

setting temp
Run Code Online (Sandbox Code Playgroud)

如果我将以下内容添加到脚本的末尾:

print "banana"
print "apple"
Run Code Online (Sandbox Code Playgroud)

这两行都按预期打印.

如果我从终端运行上面的python脚本(使用python -u,或者只是python),结果完全相同.我想我错过了一些非常愚蠢的东西.谢谢

python python-2.7

1
推荐指数
1
解决办法
2853
查看次数

标签 统计

python ×2

properties ×1

python-2.7 ×1