Python:在构造默认值时使用姐妹参数

时间:2017-05-30 17:05:03

标签: python python-2.7

我知道我可以在scala中执行此操作,但有没有办法在python中执行类似的操作:

data
data/config
None

我期待的输出是:

class ObjectXChanger {
    String name;
    int age;

    public ObjectXChanger(ObjectX objectX) {
        this.name = objectX.getName();
        this.age = objectX.age();
    }

    public void changeName(String name) {
        this.name = name;
    }

    public void changeAge(int age) {
        this.age = age;
    }

    public ObjectX getModifiedObjectX() {
        // If your builder is static, there should be no need to 
        // create a new builder each time you want a new ObjectX.
        // This line should be ObjectXBuilder.build(this.name, this.age);
        return (new ObjectXBuilder(this.name, this.age).build());
    }
}
// In your usage of ObjectX in Component B
class ComponenetB {

receivingObjectXMethod(ObjectX x){
    // If we want to change based on age
    if(x.getAge() > 10) {
         // pun intended
         ObjectXChanger xChanger = new ObjectXChanger(x);
         // Modifies the age here
         xChanger.changeAge(20);
         // x now is a reference to the new ObjectX
         x = xChanger.getModifiedObjectX;
    } 
    println(x.getName() + x.getAge());
}

谢谢!

2 个答案:

答案 0 :(得分:5)

这不是直接支持的。我会这样做,就像Python避免可变的默认实例一样:

def validate_config(data_dir, config_file_dir=None, json_schema=None):
    if config_file_dir is None:
        config_file_dir = data_dir + '/config'
    # rest of code here

答案 1 :(得分:2)

不完全是,因为在编译函数定义时会评估Python的默认args。但您可以使用None作为默认arg并在运行时检查它,如下所示:

def validate_config(data_dir, config_file_dir=None, json_schema=None):
    if config_file_dir is None:
       config_file_dir = data_dir + '/config'
    print(data_dir)
    print(config_file_dir)
    print(json_schema)

validate_config('data')

<强>输出

data
data/config
None