Python object-oriented programming OOP -- composition and derivation of classes

Catalogue

1. Combination of classes

2. Derivation of class

2.1 derivative demonstration

2.2 derivation from standard classes

2.2.1 derivation of immutable types

2.2.2 derivation of variable types

2.2.3 customizing classes with special methods

There are two ways to use existing classes in new code.

  1. The first is composition, which is to mix different classes and add them to other classes to increase function and code reusability. This is applicable to the case that a large class is composed of multiple small classes, and there is no need to modify the small class too much.
  2. The second is through derivation. It is more reasonable to use derivation when you need to design the same class but have different functions.

1. Combination of classes

As can be seen from the following code, the class home is composed of Man and House. The parent class of home is still object. This implementation is very simple. Home is not a subclass of Man and House.

class Man(object):
    '''
    This class is used to describle human!
    '''
    def __init__(self,name,birthYear):
        self.name=name
        self.birthYear=birthYear
    
class House(object):
    '''
    This class is used to describle house!
    '''
    def __init__(self,location,size,value):
        self.loc=location
        self.size=size
        self.value=value
        
class Home(object):
    '''
    This class is used to describle home,
    including different man and one house at least!
    '''
    def __init__(self,name,birthYear,location,size,value):
        self.homeowner=Man(name,birthYear)
        self.house=House(location,size,value)

allen_home=Home("allen",1982,"BeiJing",100,500)
print(allen_home.homeowner.name)
print(allen_home.homeowner.birthYear)
print(allen_home.house.loc)
print(allen_home.house.size)
print(allen_home.house.value)

 

2. Derivation of class

2.1 derivative demonstration

Derivation occurs in the process of creating subclasses, and is together with inheritance. Take the following code as an example.

First create the parent class Man, and then create two subclasses Teacher and Singer.    

  • Teacher not modified__ init__ Method, that is, follow the parent class Man__ init__, This is called inheritance.
  • Modification of Singer display__ init__ Method, which not only follows the parent class Man__ init__, There are also modifications applicable to Singer. Note that if you explicitly modify__ init__ Method, but also keep the parent class__ init__, Be sure to write it out! Both of the following can be written.

                a) super(Singer,self).__init__(name,age)

                b) super().__init__(name,age)

  • Teacher/Singer shows that the} work method is modified, that is, the work method of the parent class Man is overridden, which is called derivation.
  • The parent class of Teacher/Singer is Man.
  • The result of Teacher/Singer calling the work method is different, which is called polymorphism.
class Man(object):
    '''
    This class is used to describle human!
    '''
    def __init__(self,name,age):
        self.name=name
        self.age=age
    
    def work(self):
        print("Now a man is working")

class Teacher(Man):
    '''
    This class is used to describle worker!
    '''
    #Not modified here__ init__ , That is, the parent class Man is used
    #This is called inheritance
    
    
    #Redefine the work method, which is derived
    def work(self):
        print("Now a teacher is teaching!")

class Singer(Man):
    '''
    This class is used to describle singer!
    '''
    def __init__(self,name,age,country):
        # Call the initialization method of the parent class__ init__
        super().__init__(name,age)
        self.country=country

    #Redefine the work method, which is derived
    def work(self,song):
        print("Now a singer is singing "+song+" !")

t=Teacher("teach",33)
s=Singer("sin",28,"China")
t.work()
s.work("Sweet honey")

 

2.2 derivation from standard classes

2.2.1 derivation of immutable types

Here are two types of rewriting of float and str. just have a look.

class UpdatedFloat(float):
    def __new__(cls,val):
        return(float.__new__(cls,round(val,2)))
class UpdatedStr(str):
    def __new__(cls,string):
        return(str.__new__(cls,string[0:5]))
a=UpdatedFloat(1.123456)
b=UpdatedStr("abcdefghi")
print(a)
print(b)

2.2.2 derivation of variable types

Take the list as an example. This Updated List is no different from an ordinary list. The only difference is that each time you add elements to it, you will be prompted.

class UpdatedList(list):
    def append(self,ele):
        super().append(ele)
        print("One element is appended!")
a=UpdatedList()
a.append("a")
a.append("b")
a

2.2.3 customizing classes with special methods

In Python object-oriented programming OOP -- basic concepts of classes and instances Some special methods of classes are described in. If you customize these special methods, you will get classes with special functions.

I think this article is very well written. I recommend you to read it.

        The meaning of special methods used to customize classes in python

'''

If you think it's OK, please point a praise or collection, and think of a blog to increase popularity. Thank you very much!

'''

Keywords: Python Back-end

Added by nanban on Thu, 06 Jan 2022 04:08:38 +0200