property:init()中的set setter

时间:2017-11-09 14:34:21

标签: python

我有一个像这样的简单类:

class TestVolume:

    def __init__(self, volume: float):

        self._volume = volume * 1000
        self.volume = self._volume


    @property
    def volume(self):
        return self._volume / 1000


    @volume.setter
    def volume(self, value):
        if value <= 0:
            raise ValueError("Volume must be > 0")
        self._volume = value

基本上,我用卷实例化一个TestVolume对象,该对象应始终为正浮点数。

我希望volume属性是该类的属性。但我也想在创建对象时检查音量。这是正确的方法吗?

2 个答案:

答案 0 :(得分:0)

setter是(大多数情况下)唯一需要直接修改_volume的方法。只需使用__init__中的属性即可;你是否试图抓住设定者可能提出的ValueError取决于你。

def __init__(self, volume: float):
    try:
        self.volume = volume * 1000
    except ValueError:
        self.volume = 0

这里,__init__正在实施在创建对象时将负数量转换为0的策略;设置者的其他用户可以自行决定在发生异常时该怎么做。

答案 1 :(得分:0)

您的代码是正确的,但它不适用于创建新对象。我不熟悉import UIKit class ViewController: UIViewController { var imageStrings:[String] = [] var myScrollView:UIScrollView! @IBOutlet weak var previewView: UIImageView! var scrollWidth : CGFloat = 320 let scrollHeight : CGFloat = 100 let thumbNailWidth : CGFloat = 80 let thumbNailHeight : CGFloat = 80 let padding: CGFloat = 10 override func viewDidLoad() { super.viewDidLoad() imageStrings = ["image01","image02","image03","image04","image05","image06","image07","image08"] scrollWidth = self.view.frame.width //setup scrollView myScrollView = UIScrollView(frame: CGRectMake(0, self.view.frame.height - scrollHeight, scrollWidth, scrollHeight)) //setup content size for scroll view let contentSizeWidth:CGFloat = (thumbNailWidth + padding) * (CGFloat(imageStrings.count)) let contentSize = CGSize(width: contentSizeWidth ,height: thumbNailHeight) myScrollView.contentSize = contentSize myScrollView.autoresizingMask = UIViewAutoresizing.FlexibleWidth for(index,value) in enumerate(imageStrings) { var button:UIButton = UIButton.buttonWithType(.Custom) as! UIButton //calculate x for uibutton var xButton = CGFloat(padding * (CGFloat(index) + 1) + (CGFloat(index) * thumbNailWidth)) button.frame = CGRectMake(xButton,padding, thumbNailWidth, thumbNailHeight) button.tag = index let image = UIImage(named:value) button.setBackgroundImage(image, forState: .Normal) button.addTarget(self, action: Selector("changeImage:"), forControlEvents: .TouchUpInside) myScrollView.addSubview(button) } previewView.image = UIImage(named: imageStrings[0]) self.view.addSubview(myScrollView) } // Do any additional setup after loading the view, typically from a nib. override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func changeImage(sender:UIButton){ let name = imageStrings[sender.tag] previewView.image = UIImage(named: name) } } 访问@property的方法。 (Python 2.7)你可以做的是插入一个断言语句。如果用户输入无效,则会抛出错误。如果要设置默认值,可以在__init__块中将其包围。

try.. catch

其余代码保持不变。