python 3 stack development-object-oriented binding method (the difference between classmethod and static method), polymorphism, encapsulated property

Keywords: Python Attribute P4

I. Object-Oriented Binding Method

I. Functions defined in a class are divided into two main categories

1. Binding method (who is bound to, who calls it, automatically passes it in as the first parameter):

1. Methods bound to classes: methods decorated with classmethod decorators.

Customize classes

Classes are automatically passed in as the first parameter (in fact, objects can be called, but classes are still passed in as the first parameter)

2. Method of binding to an object: a method that is not decorated by any ornament.

Customize for the object

Objects are automatically passed in as the first parameter (functions that belong to a class can be invoked, but must follow the rules of the function, not automatically passed values)

2: Unbound methods:

Method of Decorating with Static Method Decorator

1. Classes and objects can be invoked without being bound to classes or objects, but there is no automatic value passing. It's just a common tool.

Note: Distinguished from binding to object methods, functions directly defined in classes, which are not decorated by any decorator, are methods bound to objects, not ordinary functions. Object calls this method will automatically pass values, while static method decorated methods, no matter who calls them, do not automatically pass values.

Binding Method

Class methods bound to classes

classmehtod is for classes, which are bound to classes. When classes are used, classes pass themselves as parameters to the first parameter of class methods (even if they are called by objects, classes are passed in as first parameters). python built-in the function classmethod to define functions in classes as class methods.

#setting.py  Content of the document
NAME="duoduo"
AGE=18
 
import settings

class People:
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def tell(self):
        print('%s: %s' %(self.name,self.age))

    @classmethod    #python3 The built-in function is the decorator
    def from_conf(cls):  #There cls,It's the name of a class. self It is agreed that the object is the same.
        return cls(settings.NAME,settings.AGE)

p4=People.from_conf()    #Here we find that we don't need to pass in classes anymore.
p4.tell()    

3. Non-binding methods

A function decorated with static method inside a class is a non-binding method, which is a normal function.

statimethod is not bound to classes or objects. Anyone can call it. There is no automatic value transfer effect.

import settings
import hashlib
import time

class People:
    def __init__(self,name,age):
        self.uid=self.create_id()
        self.name=name
        self.age=age

    def tell(self):
        print('%s: %s: %s' %(self.uid,self.name,self.age))

    @staticmethod   #with classmethod Both are built-in functions and decorators
    def create_id():
        m=hashlib.md5()
        m.update(str(time.clock()).encode('utf-8'))
        return m.hexdigest()

obj=People('duoduo',18)
print(obj.create_id())    #It's normal to call here without auto-passing value.
print(People.create_id())

II. Property of Packaging

1. What is feature property?

Property is a special property that is accessed by performing a function and returning a value.

Example: BMI index (bmi is calculated, but obviously it sounds like an attribute rather than a method, if we make it an attribute, it's easier to understand)

BMI values for adults:
Too light: below 18.5
Normal: 18.5-23.9
Overweight: 24-27
Obesity: 28-32
Very obese, over 32
Body mass index (BMI) = body weight (kg) = height ^ 2 (m)
  EX: 70kg÷(1.75×1.75)=22.86
class People:
    def __init__(self,name,weight,height):
        self.name=name
        self.weight=weight
        self.height=height
    @property
    def bmi(self):
        return self.weight / (self.height * self.height)
duoduo=People('duoduo',70,1.70)
# But apparently human bmi Value sounds more like a noun than a verb
# print(duoduo.bmi())  # Call before decorator is not used
# So we need to bmi This function adds a decorator to disguise it as a data attribute
# duoduo.weight=65   #change duoduo Of weight
# print(duoduo.bmi) #22.49134948096886,call duoduo.bmi The essence is trigger function. bmi Execution to get its return value
# print(duoduo.bmi)

2. Why use property

After defining a function of a class as a feature, obj.name is unaware that its name is executed by a function and then calculated when the object is reused. The use of this feature follows the principle of uniform access.

Besides

class People:
    def __init__(self,name):
        self.__name=name

    @property
    def name(self): #obj.name
        print('What you are visiting now is the username...')
        return self.__name

    @name.setter #obj.name='DUODUO'
    def name(self,x):
        # print('=================',x)
        if type(x) is not str:
            raise TypeError('The name must be str Type, silly fork')
        self.__name=x

    @name.deleter
    def name(self):
        # print('Do not let you delete')
        del self.__name

# obj=People('duoduo')
# print(obj.name)
# obj.name='DUODUO'   #Modify the name attribute to DUODUO
# print(obj.name)
# del obj.name               #Delete name attributes
# obj.name             #After deletion, read the error report

3. Encapsulation and Expansibility

Encapsulation is to distinguish between inside and outside so that the class implementer can modify the contents of the encapsulation without affecting the code of the external caller; while the external user only knows one interface (function), as long as the name and parameters of the interface (function) remain unchanged, the user's code will never need to change. This provides a good basis for collaboration -- or, as long as the basic convention of interfaces remains unchanged, code changes are not enough to worry about.

#Class Designer
class Room:
    def __init__(self,name,owner,width,length,high):
        self.name=name
        self.owner=owner
        self.__width=width
        self.__length=length
        self.__high=high
    def tell_area(self): #The external interface hides the internal implementation details. At this time, what we want is the area.
        return self.__width * self.__length

#User
>>> r1=Room('Bedroom','duoduo',20,20,20)
>>> r1.tell_area() #User Call Interface tell_area
400

#Designers of classes easily extend their functions, while users of classes do not need to change their code at all.
class Room:
    def __init__(self,name,owner,width,length,high):
        self.name=name
        self.owner=owner
        self.__width=width
        self.__length=length
        self.__high=high
    def tell_area(self): #Externally provided interfaces hide internal implementations. At this point, we want volume.,The internal logic has changed.,
#It can be implemented simply by fixing the following line, and the external calls are not perceived. This method is still used, but the function has changed.
return self.__width * self.__length * self.__high #For those still in use tell_area For interface people, new functions can be used without changing their code at all. >>> r1.tell_area() 8000

3. Polymorphism

1. What is polymorphism?

Polymorphism refers to the fact that a class of things has many forms.

Example: there are many forms of animals: humans, dogs and pigs.

import abc  #Call the built-in module abc
class Animal(metaclass=abc.ABCMeta): #Same kind of thing:Animal
    @abc.abstractmethod   #When the following subclass does not have a talk method, it will report an error.
    def talk(self):
        pass
class People(Animal): #One of the animal forms:people
    def talk(self):
        print('say hello')
class Dog(Animal): #Animal Morphology II:Dog
    def talk(self):
        print('say wangwang')
class Pig(Animal): #Animal Morphology III:pig
    def talk(self):
        print('say aoao')

2. Polymorphism

1) What is polymorphism?

Polymorphism refers to the use of instances without considering the type of instances:

For example: teacher, the bell rings (), student, the bell rings (), the teacher executes the off-duty operation, and the student executes the off-school operation. Although the two messages are the same, the effect of the execution is different.

2) Polymorphism is divided into static polymorphism and dynamic polymorphism.

Static polymorphism: Operator + can be used for any type of operation

Dynamic polymorphism:

peo=People()
dog=Dog()
pig=Pig()

#peo, dog and pig are all animals, so long as they are animals, there must be talk ing methods.
#So we can use them directly without considering the specific types of them.
peo.talk()
dog.talk()
pig.talk()

#Further, we can define a unified interface to use
def func(obj):
    obj.talk()

3. Why use polymorphism (the benefits of polymorphism)

In fact, you can see from the above examples of polymorphism that we have not added any new knowledge, that is to say, python itself supports polymorphism, what are the benefits of doing so?

1) Increased flexibility of procedures

The user calls in the same form, regardless of the variety of objects.

2) Increased program scalability

By inheriting animal classes, a new class is created. Users do not need to change their code, or use func(animal) to invoke it.

class Cat(Animal): #Another form of animal: cat
    def talk(self):
        print('say miao')

   def func(animal): #For users, there is no need to change their code at all.
      animal.talk()

cat1=Cat() #Exemplify a cat
func(cat1) #Cats can be invoked without even changing the way they are invoked. talk function
say miao

#So we added a new form. Cat,from Cat Instances of class generation cat1,Users can change their code without any need at all.
#Use the same way as people, dogs and pigs. cat1 Of talk Method, namely func(cat1)

4. Duck type

Comic hour:

Python advocates the type of duck, that is,'If it looks like, calls like, and walks like a duck, then it's a duck'.

python programmers usually write programs based on this behavior. For example, if you want to write a custom version of an existing object, you can inherit that object

You can also create a completely new object that looks and acts like it, but has nothing to do with it, which is usually used to preserve the loosely coupled degree of program components.

Example 1: Using various `file-like'objects defined in the standard library, although these objects work like files, they have no way of inheriting built-in file objects

#Both are like ducks.,Both look like files,So it can be used as a file.
class TxtFile:
    def read(self):
        pass

    def write(self):
        pass

class DiskFile:
    def read(self):
        pass
    def write(self):
        pass

Example 2: In fact, we have been enjoying the benefits of polymorphism. For example, Python's sequence type has many forms: string, list, tuple, polymorphism as follows

#str,list,tuple Both are sequence types
s=str('hello')
l=list([1,2,3])
t=tuple((4,5,6))

#We can use it without considering the three types. s,l,t
s.__len__()
l.__len__()
t.__len__()

len(s)
len(l)
len(t)

Posted by zsxdcfv21 on Thu, 10 Jan 2019 01:18:13 -0800