I am absolutly new in Python (I came from Java) and I have the following doubts about class fields.
Considering a code like this:
class Toy():
def __init__(self, color, age):
self.color = color
self.age = age
action_figure = Toy('red', 10)
Ok, what is done it is clear and very simple:
it is defining a Toy class. In the constructor method is defining two fields and how to set the fields value. Finnally (in the "main") it is created a new Toy instance passing the values of the field in the constructor call.
Ok, clear...but I have a doubt. In Java to define the same class I do something like this:
public class Toy {
private String color;
private int age;
// CONSTRUCTOR:
public Dog(String color, int age) {
this.color = color;
this.age = age;
}
}
Ok, it is similar but I have figoured out a pretty big difference. In my Java conde I declare the class fields as variable outside my constructor method. In Python I am defining the class fields directly inside the constructor method. So it means that in Java I can declare n class fields and use the constructor method to initialized only a subset of this fields, for example something like this:
public class Toy {
private String color;
private int age;
private String field3;
private String field4;
private String field5;
// CONSTRUCTOR:
public Dog(String color, int age) {
this.color = color;
this.age = age;
}
}
where I have also the field3, field4 and field5 fields that will be not initialized by my constructor (in case I can set theyr value in a second time using a setter method).
Can I do something similar in Python? Can I declar class fields outside the constructor method?