Python Class

24 篇文章 0 订阅

official doc:

quick tutorial from: Python Classes and Objects - GeeksforGeeks

Python Classes and Objects

  • Difficulty Level : Easy
  • Last Updated : 10 Jun, 2021

A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by their class) for modifying their state.

To understand the need for creating a class let’s consider an example, let’s say you wanted to track the number of dogs that may have different attributes like breed, age. If a list is used, the first element could be the dog’s breed while the second element could represent its age. Let’s suppose there are 100 different dogs, then how would you know which element is supposed to be which? What if you wanted to add other properties to these dogs? This lacks organization and it’s the exact need for classes. 

Class creates a user-defined data structure, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object.

Some points on Python class:  

  • Classes are created by keyword class.
  • Attributes are the variables that belong to a class.
  • Attributes are always public and can be accessed using the dot (.) operator. Eg.: Myclass.Myattribute
Class Definition Syntax:

class ClassName:
    # Statement-1
    .
    .
    .
    # Statement-N

Defining a class –

# Python3 program to

# demonstrate defining

# a class

class Dog:

    pass

In the above example, the class keyword indicates that you are creating a class followed by the name of the class (Dog in this case).
 

Class Objects

An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. It’s not an idea anymore, it’s an actual dog, like a dog of breed pug who’s seven years old. You can have many dogs to create many different instances, but without the class as a guide, you would be lost, not knowing what information is required.
An object consists of : 

  • State: It is represented by the attributes of an object. It also reflects the properties of an object.
  • Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.
  • Identity: It gives a unique name to an object and enables one object to interact with other objects.

python class

Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.

Example:
 

python declaring an object

Declaring an object – 

# Python3 program to

# demonstrate instantiating

# a class

class Dog:

     

    # A simple class

    # attribute

    attr1 = "mammal"

    attr2 = "dog"

    # A sample method 

    def fun(self):

        print("I'm a", self.attr1)

        print("I'm a", self.attr2)

# Driver code

# Object instantiation

Rodger = Dog()

# Accessing class attributes

# and method through objects

print(Rodger.attr1)

Rodger.fun()

Output: 

mammal
I'm a mammal
I'm a dog

In the above example, an object is created which is basically a dog named Rodger. This class only has two class attributes that tell us that Rodger is a dog and a mammal.
 

The self

  • Class methods must have an extra first parameter in the method definition. We do not give a value for this parameter when we call the method, Python provides it.
  • If we have a method that takes no arguments, then we still have to have one argument.
  • This is similar to this pointer in C++ and this reference in Java.

When we call a method of this object as myobject.method(arg1, arg2), this is automatically converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self is about.
 

__init__ method

The __init__ method is similar to constructors in C++ and Java. Constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. It runs as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object.

# A Sample class with init method

class Person:

   

    # init method or constructor 

    def __init__(self, name):

        self.name = name

   

    # Sample Method 

    def say_hi(self):

        print('Hello, my name is', self.name)

   

p = Person('Nikhil')

p.say_hi()

Output: 

Hello, my name is Nikhil

Class and Instance Variables

Instance variables are for data, unique to each instance and class variables are for attributes and methods shared by all instances of the class. Instance variables are variables whose value is assigned inside a constructor or method with self whereas class variables are variables whose value is assigned in the class.

Defining instance variable using a constructor. 

# Python3 program to show that the variables with a value 

# assigned in the class declaration, are class variables and

# variables inside methods and constructors are instance

# variables.

    

# Class for Dog

class Dog:

   

    # Class Variable

    animal = 'dog'            

   

    # The init method or constructor

    def __init__(self, breed, color):

     

        # Instance Variable    

        self.breed = breed

        self.color = color       

    

# Objects of Dog class

Rodger = Dog("Pug", "brown")

Buzo = Dog("Bulldog", "black")

print('Rodger details:')  

print('Rodger is a', Rodger.animal)

print('Breed: ', Rodger.breed)

print('Color: ', Rodger.color)

print('\nBuzo details:')  

print('Buzo is a', Buzo.animal)

print('Breed: ', Buzo.breed)

print('Color: ', Buzo.color)

# Class variables can be accessed using class

# name also

print("\nAccessing class variable using class name")

print(Dog.animal)       

Output: 

Rodger details:
Rodger is a dog
Breed:  Pug
Color:  brown

Buzo details:
Buzo is a dog
Breed:  Bulldog
Color:  black

Accessing class variable using class name
dog

Defining instance variable using the normal method.

# Python3 program to show that we can create 

# instance variables inside methods

    

# Class for Dog

class Dog:

       

    # Class Variable

    animal = 'dog'     

       

    # The init method or constructor

    def __init__(self, breed):

           

        # Instance Variable

        self.breed = breed            

   

    # Adds an instance variable 

    def setColor(self, color):

        self.color = color

       

    # Retrieves instance variable    

    def getColor(self):    

        return self.color   

   

# Driver Code

Rodger = Dog("pug")

Rodger.setColor("brown")

print(Rodger.getColor()) 

Output:  

brown

Inheritance in Python

from: Inheritance in Python - GeeksforGeeks

  • Difficulty Level : Easy
  • Last Updated : 14 Sep, 2020

Inheritance is the capability of one class to derive or inherit the properties from another class. The benefits of inheritance are: 

  1. It represents real-world relationships well.
  2. It provides reusability of a code. We don’t have to write the same code again and again. Also, it allows us to add more features to a class without modifying it.
  3. It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A.

Below is a simple example of inheritance in Python 

# A Python program to demonstrate inheritance 

   

# Base or Super class. Note object in bracket.

# (Generally, object is made ancestor of all classes)

# In Python 3.x "class Person" is 

# equivalent to "class Person(object)"

class Person(object):

       

    # Constructor

    def __init__(self, name):

        self.name = name

   

    # To get name

    def getName(self):

        return self.name

   

    # To check if this person is an employee

    def isEmployee(self):

        return False

   

   

# Inherited or Subclass (Note Person in bracket)

class Employee(Person):

   

    # Here we return true

    def isEmployee(self):

        return True

   

# Driver code

emp = Person("Geek1"# An Object of Person

print(emp.getName(), emp.isEmployee())

   

emp = Employee("Geek2") # An Object of Employee

print(emp.getName(), emp.isEmployee())

Output: 

Geek1 False
Geek2 True

What is object class? 
Like Java Object class, in Python (from version 3.x), object is root of all classes. 
In Python 3.x, “class Test(object)” and “class Test” are same. 
In Python 2.x, “class Test(object)” creates a class with object as parent (called new style class) and “class Test” creates old style class (without object parent). Refer this for more details.

Subclassing (Calling constructor of parent class) 
A child class needs to identify which class is its parent class. This can be done by mentioning the parent class name in the definition of the child class. 
Eg: class subclass_name (superclass_name)

# Python code to demonstrate how parent constructors

# are called.

  

# parent class

class Person( object ):    

  

        # __init__ is known as the constructor         

        def __init__(self, name, idnumber):   

                self.name = name

                self.idnumber = idnumber

        def display(self):

                print(self.name)

                print(self.idnumber)

  

# child class

class Employee( Person ):           

        def __init__(self, name, idnumber, salary, post):

                self.salary = salary

                self.post = post

  

                # invoking the __init__ of the parent class 

                Person.__init__(self, name, idnumber) 

  

                  

# creation of an object variable or an instance

a = Employee('Rahul', 886012, 200000, "Intern")    

  

# calling a function of the class Person using its instance

a.display() 

Output: 

Rahul
886012

‘a’ is the instance created for the class Person. It invokes the __init__() of the referred class. You can see ‘object’ written in the declaration of the class Person. In Python, every class inherits from a built-in basic class called ‘object’. The constructor i.e. the ‘__init__’ function of a class is invoked when we create an object variable or an instance of the class.

The variables defined within __init__() are called as the instance variables or objects. Hence, ‘name’ and ‘idnumber’ are the objects of the class Person. Similarly, ‘salary’ and ‘post’ are the objects of the class Employee. Since the class Employee inherits from class Person, ‘name’ and ‘idnumber’ are also the objects of class Employee.
If you forget to invoke the __init__() of the parent class then its instance variables would not be available to the child class. 

The following code produces an error for the same reason.

# Python program to demonstrate error if we

# forget to invoke __init__() of the parent.

  

class A:

      def __init__(self, n = 'Rahul'):

              self.name = n

class B(A):

      def __init__(self, roll):

              self.roll = roll

  

object = B(23)

print (object.name)

Output : 

Traceback (most recent call last):
  File "/home/de4570cca20263ac2c4149f435dba22c.py", line 12, in 
    print (object.name)
AttributeError: 'B' object has no attribute 'name'

Different forms of Inheritance: 
1. Single inheritance: When a child class inherits from only one parent class, it is called single inheritance. We saw an example above.
2. Multiple inheritance: When a child class inherits from multiple parent classes, it is called multiple inheritance. 
Unlike Java and like C++, Python supports multiple inheritance. We specify all parent classes as a comma-separated list in the bracket.

# Python example to show the working of multiple 

# inheritance

class Base1(object):

    def __init__(self):

        self.str1 = "Geek1"

        print("Base1")

  

class Base2(object):

    def __init__(self):

        self.str2 = "Geek2"        

        print("Base2")

  

class Derived(Base1, Base2):

    def __init__(self):

          

        # Calling constructors of Base1

        # and Base2 classes

        Base1.__init__(self)

        Base2.__init__(self)

        print("Derived")

          

    def printStrs(self):

        print(self.str1, self.str2)

         

  

ob = Derived()

ob.printStrs()

Output: 

Base1
Base2
Derived
Geek1 Geek2

3. Multilevel inheritance: When we have a child and grandchild relationship.

# A Python program to demonstrate inheritance 

  

# Base or Super class. Note object in bracket.

# (Generally, object is made ancestor of all classes)

# In Python 3.x "class Person" is 

# equivalent to "class Person(object)"

class Base(object):

      

    # Constructor

    def __init__(self, name):

        self.name = name

  

    # To get name

    def getName(self):

        return self.name

  

  

# Inherited or Sub class (Note Person in bracket)

class Child(Base):

      

    # Constructor

    def __init__(self, name, age):

        Base.__init__(self, name)

        self.age = age

  

    # To get name

    def getAge(self):

        return self.age

  

# Inherited or Sub class (Note Person in bracket)

class GrandChild(Child):

      

    # Constructor

    def __init__(self, name, age, address):

        Child.__init__(self, name, age)

        self.address = address

  

    # To get address

    def getAddress(self):

        return self.address        

  

# Driver code

g = GrandChild("Geek1", 23, "Noida")  

print(g.getName(), g.getAge(), g.getAddress())

Output: 

Geek1 23 Noida

4. Hierarchical inheritance More than one derived classes are created from a single base.

5. Hybrid inheritance: This form combines more than one form of inheritance. Basically, it is a blend of more than one type of inheritance.

Private members of parent class 
We don’t always want the instance variables of the parent class to be inherited by the child class i.e. we can make some of the instance variables of the parent class private, which won’t be available to the child class. 
We can make an instance variable by adding double underscores before its name. For example,

# Python program to demonstrate private members

# of the parent class

class C(object):

       def __init__(self):

              self.c = 21

  

              # d is private instance variable 

              self.__d = 42    

class D(C):

       def __init__(self):

              self.e = 84

              C.__init__(self)

object1 = D()

  

# produces an error as d is private instance variable

print(object1.d)                     

Output : 

  File "/home/993bb61c3e76cda5bb67bd9ea05956a1.py", line 16, in 
    print (object1.d)                     
AttributeError: type object 'D' has no attribute 'd'

Since ‘d’ is made private by those underscores, it is not available to the child class ‘D’ and hence the error.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值