I am absolutely new to Python (I came from Java) and I have the following doubts about class fields.
Considering code like this:
class Toy():
def __init__(self, color, age):
self.color = color
self.age = age
action_figure = Toy('red', 10)
What is done is clear and very simple:
it is defining a Toy
class. The constructor is defining two fields setting their values. Finally (in main
) a new Toy
instance is created, passing the values of the fields in the constructor call.
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;
}
}
It is similar, but I have figured out a pretty big difference. In my Java code I declare the class fields as variables outside my constructor. In Python I am defining the class fields directly inside the constructor. So it means that in Java I can declare several fields and use the constructor method to initialize only a subset of these 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 also have the field3
, field4
and field5
fields that will be not initialized by my constructor. (In case I can set their value subsequently with a setter method.)
Can I do something similar in Python? Can I declare class fields outside the constructor method?