Python instance parent class

Parents And Children In Python

As you might know, creating a fully functional class in an object-oriented programming language is time-consuming because real classes perform a lot of complex tasks.

In Python, you can get the features you want from an existing class(parent) to create a new class(child). This Python feature is called inheritance.

  • obtain the features of a parent class,
  • change the features that you don’t need,
  • add new features to your child class. (derived class or subclass)

Since you are using a pre-used, tested class, you don’t have to put quite as much effort into your new class. The child class inherits the attributes and functions of its parent class.

If we have several similar classes, we can define the common functionalities of them in one class and define child classes of this parent class and implement specific functionalities there.

Three Data Professionals

We have 3 data professionals. They all know mathematics and statistics, SQL, and a programming language like Python, R, Java, etc.

class Data_Scientist: 
def __init__(self, name, SQL):
self.name = name
self.SQL = SQL
def knows_maths_stats(self):
return True
def knows_programming(self):
return True

class Data_Analyst:
def __init__(self, name, SQL):
self.name = name
self.SQL = SQL
def knows_maths_stats(self):
return True
def knows_programming(self):
return True

class Data_Engineer:
def __init__(self, name):
self.name = name
self.SQL = SQL
def knows_maths_stats(self):
return True
def knows_programming(self):
return True

Instead of writing the same class again and again, we can define a parent class “Data_Professional” and 3 child classes of the Data_Professional class: Data_Analyst, Data_Scientist, and Data_Engineer.

Читайте также:  Unique page title - My Site

Источник

Python instance parent class

Last updated: Feb 21, 2023
Reading time · 4 min

banner

# Table of Contents

# Accessing parent class attributes in Python

To access parent class attributes in a child class:

  1. Use the super() method to call the constructor of the parent in the child.
  2. The __init__() method will set the instance variables.
  3. Access any of the parent class’s attributes or methods on the self object.
Copied!
class Employee(): cls_id = 'emp-cls' def __init__(self, name): self.salary = 100 self.name = name class Developer(Employee): def __init__(self, name): # 👇️ invoke parent __init__() method super().__init__(name) # 👇️ accessing parent instance variable print(self.salary) # 👉️ 100 # 👇️ accessing parent class variable print(self.cls_id) # 👉️ emp-cls d1 = Developer('bobbyhadz') print(d1.salary) # 👉️ 100 print(d1.cls_id) # 👉️ 'emp-cls'

access parent class attributes in python

The code snippet shows how to access parent class variables and parent instance variables from a child class.

# Accessing parent class variables

The cls_id attribute is a class variable.

Class variables can be accessed directly on an instance of the child or the child class itself.

Copied!
class Employee(): cls_id = 'emp-cls' class Developer(Employee): def __init__(self, name): # 👇️ accessing parent class variable print(self.cls_id) # 👉️ emp-cls d1 = Developer('bobbyhadz') print(d1.cls_id) # 👉️ 'emp-cls' print(Developer.cls_id) # 👉️ 'emp-cls'

accessing parent class variables

# Accessing parent instance variables

To access parent instance variables, call the class’s constructor method to run the code in the parent’s _ _ init _ _ () method.

Copied!
class Employee(): def __init__(self, name): self.salary = 100 self.name = name class Developer(Employee): def __init__(self, name): # 👇️ call parent __init__() method super().__init__(name) print(self.salary) # 👉️ 100 d1 = Developer('bobbyhadz') print(d1.salary) # 👉️ 100

accessing parent instance variables

The super() method gives us access to the base class without explicitly referring to it.

# Using super() vs the class’s name

We could replace the call to super() with Employee to achieve the same result.

Copied!
class Employee(): def __init__(self, name): self.salary = 100 self.name = name class Developer(Employee): def __init__(self, name): Employee.__init__(self, name) print(self.salary) # 👉️ 100 d1 = Developer('bobbyhadz') print(d1.salary) # 👉️ 100

using super vs class name

However, super() is more flexible and more commonly used than explicitly referring to the base class.

The call to the parent’s __init__ method runs the method and assigns the salary and name attributes to the instance.

Now we can access the parent class’s salary and name attributes on an instance of the child class.

The classes in the example assume that a name argument is required.

Here is the same example, but without passing any arguments when instantiating the child class.

Copied!
class Employee(): def __init__(self): self.salary = 100 class Developer(Employee): def __init__(self): super().__init__() print(self.salary) # 👉️ 100 d1 = Developer() print(d1.salary) # 👉️ 100

Once the code in the parent’s __init__() method runs, the instance gets assigned a salary attribute, which can be accessed on the self object.

# Accessing a method that’s defined in the Parent class

You can use the same approach to access a method defined in the parent class from the child class.

Copied!
class Employee(): def __init__(self, name): self.salary = 100 self.name = name def greet(self): print(f'Hello self.name>') class Developer(Employee): def __init__(self, name): super().__init__(name) print(self.salary) # 👉️ 100 self.greet() # 👉️ Hello bobbyhadz d1 = Developer('bobbyhadz') print(d1.salary) # 👉️ 100 d1.greet() # 👉️ Hello bobbyhadz

accessing method that is defined in parent class

The parent defines a greet() method which the child instance can access via the self object.

# Get the name of a Parent class in Python

To get the name of a parent class:

  1. Use the __bases__ attribute on the class to get a tuple of parent classes.
  2. Use a for loop to iterate over the tuple.
  3. Use the __name__ attribute on each class to get the name of the parent classes.
Copied!
class Person(): pass class Employee(Person): pass class Developer(Employee): pass immediate_parents = Developer.__bases__ print(immediate_parents) # 👉️ (,) for parent in immediate_parents: print(parent.__name__) # 👉️ Employee print(immediate_parents[0].__name__) # 👉️ Employee

We used the class. _ _ bases _ _ attribute to get a tuple of the parent classes of a class.

# Getting the name of a Parent class when you only have access to an instance

If you only have access to an instance of the class, access the __bases__ attribute on the result of calling the type() class with the instance.

Copied!
class Person(): pass class Employee(Person): pass class Developer(Employee): pass d1 = Developer() immediate_parents = type(d1).__bases__ print(immediate_parents) # 👉️ (,) for parent in immediate_parents: print(parent.__name__) # 👉️ Employee print(immediate_parents[0].__name__) # 👉️ Employee

The type class returns the type of an object.

Источник

Python Inheritance

Inheritance allows us to define a class that inherits all the methods and properties from another class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived class.

Create a Parent Class

Any class can be a parent class, so the syntax is the same as creating any other class:

Example

Create a class named Person , with firstname and lastname properties, and a printname method:

class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

#Use the Person class to create an object, and then execute the printname method:

x = Person(«John», «Doe»)
x.printname()

Create a Child Class

To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class:

Example

Create a class named Student , which will inherit the properties and methods from the Person class:

Note: Use the pass keyword when you do not want to add any other properties or methods to the class.

Now the Student class has the same properties and methods as the Person class.

Example

Use the Student class to create an object, and then execute the printname method:

Add the __init__() Function

So far we have created a child class that inherits the properties and methods from its parent.

We want to add the __init__() function to the child class (instead of the pass keyword).

Note: The __init__() function is called automatically every time the class is being used to create a new object.

Example

Add the __init__() function to the Student class:

When you add the __init__() function, the child class will no longer inherit the parent’s __init__() function.

Note: The child’s __init__() function overrides the inheritance of the parent’s __init__() function.

To keep the inheritance of the parent’s __init__() function, add a call to the parent’s __init__() function:

Example

Now we have successfully added the __init__() function, and kept the inheritance of the parent class, and we are ready to add functionality in the __init__() function.

Use the super() Function

Python also has a super() function that will make the child class inherit all the methods and properties from its parent:

Example

By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.

Add Properties

Example

Add a property called graduationyear to the Student class:

class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019

In the example below, the year 2019 should be a variable, and passed into the Student class when creating student objects. To do so, add another parameter in the __init__() function:

Example

Add a year parameter, and pass the correct year when creating objects:

class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year

x = Student(«Mike», «Olsen», 2019)

Add Methods

Example

Add a method called welcome to the Student class:

class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year

def welcome(self):
print(«Welcome», self.firstname, self.lastname, «to the class of», self.graduationyear)

If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent method will be overridden.

Источник

Оцените статью