Xxiii, multi-state, built-in methods and magic methods, context management,

A polymorphic

"" "Polymorphism refers to a class of things have a variety of forms, (a subclass of abstract class multiple, polymorphic and thus relies on the concept of inheritance) 
Definition: polymorphism is a way to use an object, a subclass overrides the parent class method, call the same parent class method different subclasses of objects, can produce different results
benefits: call flexible, with multi-state, easier to write generic code that make generic programming in order to adapt to changing needs
Implementation steps:
1. define the parent class, and provide the public methods
2. subclassing, and override inherited methods
3. subclass object passed to the caller can see the different effects of different subclasses perform
"" "
# Demand: working with police officers and police dogs, police dogs are divided into two types: pursuit of the enemy and to trace narcotics, carry different dogs, perform different tasks 
# 1. Define the parent 

class Dog (Object): 

    DEF Work (Self):
         Pass 


# 2. define subclasses, subclasses override the parent class method: define two classes represent different dogs 
class Armydog (Dog):
     DEF Work (Self):
         Print ( " pursuit of the enemy " ) 


class Drugdog (Dog):
     DEF Work (Self):
         Print ( " tracing drugs " ) 


# define human 
class the Person:
     DEF work_with_dog (Self, Dog): 
        dog.work () 


#3. Create objects, call different functions, observe the results of 

AD = Armydog () 
du = Drugdog () 
the p- = the Person () 
p.work_with_dog (AD)

Second, the built-in method

Object / Object .__ class attribute names dict__ object or class of 
the class attribute name of the object / class __class__ object or class
type .mro () to view the inheritance, the first to the last
class /cls.__name__ class name
class .__ base__ inherited class
# Double Down Method 
# __str__ magic method 
# __repr__ 

class Teacher:
     DEF  the __init__ (Self, name, the salary): 
        the self.name = name 
        self.salary = the salary 

    DEF  __str__ (Self):
         return  " Teacher IS Object:% S " % Self .name   # in __str__ return value must be a string, otherwise an error 

    DEF  __repr__ (Self):
         return str (Self. __dict__ ) 

    DEF FUNC (Self):
         return  " Wahaha " 


tTeacher = ( " Shabi " , 10 )
 Print (T)   # printing when an object is invoked str__ .__ T 
Print (the repr (T))
 Print ( " >>>>>>> R & lt% " % T) 


# A >>>>>>>>>>> cbject str __ .__ 
# % S str () direct printing actually go __str__ 
# % S repr () actually go __repr__ 
# repr is str preparedness tires, but can not do repr str spare tire 

# Print (obj) / S% '% obj / str (obj) when, in fact, called obj .__ str__ method, str method if there is, then returned it must be a string 
# without __str__ method, this method will try to find __repr__ class, no, find the parent class __str__ 
# the repr (),Only to find __repr__, if not find the parent class 


# __len__ method 
#the Classes class: 
#      DEF the __init __ (Self, name): 
#          the self.name name = 
#          self.student = [] 
# 
#      DEF __len __ (Self): 
#          return len (self.student) 
# 
# 
# py_q10 = the Classes ( "Python full-time nine ") 
# py_q10.student.append (" better than ") 
# py_q10.student.append (" foolish ") 
# Print (len (py_q10)) 


# __del__ method 
# class A: 
#      DEF __del __ (Self ): # destructor; finishing touches before deleting objects 
#          self.f.close () 
# 
# 
# A = A () 
#af = open () # open file, open a file in a first operating system, the presence of the operator to get the file in memory 
# del A # delete both variables, and execution method, the first execution method, delete 


# has been deleted, error 

# __call__ 
class A:
     DEF  __init__ (Self, name): 
        self.name = name 

    DEF  __call__ (Self):
         Print ( " the implementation of my friends " ) 


A = A ( " alex " ) 
A ()   # execute my friends
Three, item series 
__getitem __ \ __ setitem __ \ __ del__item
class Foo:
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex

        # 获取

    def __getitem__(self, item):
        if hasattr(self, item):
            return self.__dict__[item]
        # 设置,修改

    def __setitem__(self, key, value):
        self.__dict__[key] = value

    def __delitem__(self, key):
        del self.__dict__[key]


f = Foo("tank", 18, "")
print(f["name"])  # tank
print(f["age"])  # 18
f["hobby"] = ""
print(f.hobby, f["hobby"])
# del f["hobby"]  # 删除
print(f.__dict__)

Fourth, context management

When performing with the statement, it will first perform the Enter, 
#
# code execution when executing exit after completion, or code encounters an exception will perform exit immediately, passing the error message
#
# contains type of error. The error message Error tracking information
#
# Note:
#
# `` `Python
# the Enter function should return the object itself
# exit function can return a value, a bool type is used to indicate whether the exception is handled, appear only in the context of an exception is useful
# If True it means that, exceptions, and was handled
# False, an exception is not handled, the program will interrupt error
class Myopen:
    def __init__(self, path):
        self.path = path

    def __enter__(self):
        self.file = open(self.path)
        print("enter....")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("exit.........")
        self.file.close()
        return True


# m =Myopen("txt")  和下面同等
with Myopen("txt") as m:
    res = m.file.read()
    print(res)

 

Guess you like

Origin www.cnblogs.com/wukai66/p/11264218.html