Python Classes and Objects

Class

Everything in python is treated as a class. It is a client-specified model for the object. It represents the collection of properties that represents the properties of the class. The properties are the data members. We can get to these techniques utilizing dot (.) notation

We can represent the class with Class pursue by the class name. The class name should be pursued by colon (:)

Class Class_name():

Statements

Print(Class_name)

Example:
class P: 
x = 10 
print (x) 
print(P) 
Output

10

Object

It is a specific instance of the data structure. It is frequently class represent the objects. An object includes both data techniques and members.

Method

It is an exceptional sort of operation that is represented in the class representing.

Data member

These can be class variables and the instance variables. They manage the information that is related to the class and objects.

Instance

An instance is a particular object of a specific class. For instance, an object has a place with the class student, should be an instance on the class student.

Class variables

It is a variable that can be joint through class instances. These variables are pronounced inside the class but outside the techniques. Hence those are not generally utilized as instance variables.

Instance Variables

Inside the method, we can represent variables. These variables have a place with the current class example.

Features of Python OOPS

The main features of Python OOPS are as follows:

Abstraction

It can simplify the program difficulty abstraction is used. But we cannot startup the abstract class. It implies for these classes, and we cannot generate the objects and classes. We can make abstraction to inherit specific functionalities. Furthermore, we can inherit the operations, but at the similar time, we cannot instance of the specific class.

Inheritance

This is fundamentally the feature of the class. Through this idea, we can move one class features to the other. This is beneficial at the period of subclass generation. These subclasses can get the features from the parent classes. Besides, as per the client requirement, without influencing the parent functionality, therefore we can override and insert the new functionalities.

There are two classes in inheritances:

Parent class

Child class

It is generally, the child class inherits the parent class features. This Inheritance is specifically split into methods. Those are single, multilevel, hierarchical and multiple inheritances.

Single Level Inheritances

A class that is inherited from another single parent class itself is known as single inheritance.

Multiple inheritances

It defines that we are inheriting the features of numerous classes into one. In this, two classes P and Q inherits the attributes from Class R.

Multilevel inheritances

In this type of inheritance, specific properties were needed at multiple levels.

Functional overloading

It defines creating more than individual behaviour to a specific behaviour. The function here implemented differently by the parameter techniques and the objects involved.

Operator overloading

It defines authorizing higher than one function to the specific function.

Polymorphism

It is the capacity to present a similar interface in multiple primary forms. If the child class is inheriting the parents, it cannot automatically define to inherit about the parent class. In other terms, unlike parent class, it can do some things in multiple manners. Polymorphism is using inheritance.

Example
class cow(object):
def color(self):
print(“white”)
class buffalo(object):
def color(self):
print(“black”)
def animalcolor(animal Type):
animalType.color()
cowObj = cow()
bufObj = buffalo()
animalcolor(cowObj)
animal color(bufObj)
Output

white

black

Singleton Class

A singleton is a design that confines the instantiation of a class to one instance.

Example
class Singleton:
def __new__(cls):
try:
it = cls.__it__
except AttributeError:
it = cls.__it__ = object.__new__(cls)
return it
def __repr__(self):
return '<{}>'.format(self.__class__.__name__.upper())
def __eq__(self, other):
return other is self
What is a metaclass?

In Python, each variable is an object: integers, strings, records, functions, operations and classes are objects and each object is an instance of a class. It can test the class of an object x, one can call type(x), so:

Example
>>> type(5)
< type 'int'>
>>> type(str)
< type 'type'>
>>> type([1, 2, 3])
< type 'list'>
>>> class C(object):
... pass
...
>>> type(C)
< type 'type'>

Some classes in python are instances of type. type itself is additionally a class. Some classes whose instances are also classes are known as metaclasses.

Singletons using metaclasses

A singleton is a design that confines the instantiation of a class to one instance.

Example

class SingletonType(type):

def __call__(cls, *args, **kwargs):

try:

return cls.__instance

except AttributeError:

cls.__instance = super(SingletonType, cls).__call__(*args, **kwargs)

return cls.__instance

Custom operations with metaclasses

Operations in metaclasses can be modified therefore we that while a class is construct, a string is showed to regular output, or an exception is thrown. This metaclass will show the name of the class being develop.

Example

class VerboseMetaclass(type):

def __new__(cls, class_name, class_parents, class_dict):

print(“Generating class “, class_name)

new_class = super().__new__(cls, class_name, class_parents, class_dict)

return new_class

We can utilize the metaclass like so:

class Spam(metaclass=VerboseMetaclass):

def eggs(self):

print(“[insert instance string here]”)

s = Spam()

s.eggs()

Output

Creating class Spam [insert instance string here]

The default metaclass

We can have know that each variable in Python is an object. It is valid,and all objects have a class:

>>> type(1)

int

The literal 1 is an instance of int.

>>> class Foo(object):

… pass …

Descriptors and Dotted Lookups

Those are objects that are frequently attributes of classes and that have few of __get__, __set__, or __delete__ particular techniques.

Data definitions have any of __set__, or __delete__.

These can control the dotted query on an instance and are utilized to execute functions, staticmethod, classmethod, and property. A dotted query (example, instance foo of class Foo searching up attribute bar – i.e. foo.bar) utilizes the pursue algorithm:

These can control the dabbed query on occasion and are utilized to execute capacities, staticmethod, classmethod, and property. A spotted query (for example occurrence foo of class Foo looking into a characteristic bar – for example foo.bar) utilizes the accompanying calculation:

  1. bar is turned upward in the class, Foo. If it is a Data Descriptor, at that point the information descriptor is utilized. That is how property can control admittance to information in a case, and occurrences can’t supersede this.
  2. bar is turned upward in the occurrence __dict__. This is the reason we can abrogate or hinder strategies being called from an occurrence with a specked query. If the bar exists in the case, it is utilized.
  3. glance in the class Foo for the bar. On the off chance that it is a Descriptor, at that point the descriptor convention is utilized. This is how capacities (in this specific situation, unbound strategies), classmethod, and staticmethod are actualized. Else it essentially restores the item there, or there is an AttributeError.
What is Caveats?

Classes can characterize a __dir__() strategy. On the off chance that that technique exists calling dir() will call __dir__(), in any case, Python will attempt to make a rundown of individuals from the class. This implies the dir capacity can have unforeseen outcomes.

If the object doesn’t give dir(), the capacity makes an honest effort to accumulate data from the item’s dict trait, whenever characterized, and from its sort object. The subsequent rundown isn’t finished and might be off base when the item has a custom getattr().

Since dir() is provided fundamentally as accommodation for use at an intuitive brief, it attempts to flexibly a fascinating arrangement of names more than it attempts to a thoroughly or reliably characterized set of names gracefully. Its itemized conduct may change across discharges. For instance, metaclass credits are not in the outcome list when the contention is a class.

Enroll Yourself: Python Training 

Copyright 1999- Ducat Creative, All rights reserved.