sircros.blogg.se

Python oop inheritance
Python oop inheritance












In words, this says to the Python interpreter: “Okay, this object that we’re creating will have a name ( self.name), and this name is inside the name argument”. Look at the first line of the _init_ method - self.name = name. Don’t worry if it’s not completely clear now it will be in the next sections. This means that each time we want to access a certain method or variable that belongs to an instance of the class ( max or pax are two different instances), we must use the self keyword. Inside the class code, the self keyword represents the current instance of the class. It’s not a coincidence that this is the first argument of the method. As arguments of the constructor, we have the name, the breed, and a special keyword called self. This method is used to initialize the object’s state, so it assigns values to the variables of the newly created object. Every Python class has this, because it’s the default constructor. Then we bump into a method called _init_. On line 1, we declare a new class using the name Dog. Pax = Dog ( "Pax", "Labrador" ) print ( max ) print (pax )

python oop inheritance

Let’s have a look at this Python code: class Dog ( ) : def _init_ (self, name, breed ) :ĭef _repr_ (self ) : return f"Dog(name= )" max = Dog ( "Max", "Golden Retriever" ) Then, starting from the template provided by the class, we create the objects. In this example, we can model Max and Pax as objects or, in other words, as instances of a dog.īut wait, what is a dog? How can I model the idea of a dog? Using classes.Īs we can see in the picture above, a class is a template that defines the data and the behavior. Even if they are of a different breed or color, they still are dogs. What do they have in common? They are dogs and they represent the idea of a dog. Let’s say you have two dogs, called Max and Pax.

python oop inheritance

The first important concept of OOP is the definition of an object.














Python oop inheritance