OPP Some cats and dogs

1. Ducks type

  "Duck typing" dynamic language, it does not require strict inheritance hierarchy, as long as an object "looks like a duck, walks like a duck," then it can be seen as a duck.

  For statically typed languages (such as Java), if the need to pass Animalthe type of the object must be passed in Animalthe type or subclass of it, otherwise, you can not call the run()method.

  For dynamic languages such as Python, it would not necessarily need to pass Animaltype. We just need to ensure that incoming object has a run()method on it:

  For example: Python's "file-like object" is a kind of duck typing. For the real file object, it has a read()method that returns its contents. However, many objects, as long as the read()method is considered "file-like object".

  Many function receives the argument is "file-like object", you do not have to pass a real file object, can pass any implementation of read()object methods.

 

2. Get object information

1) Get the object properties, methods dir ()

>>> dir('ABC')
['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill']

   __xxx__ method, generally for special purposes, eg: __ length__

>>> len('ABC')
3
>>> 'ABC'.__len__()
3
# ---- write our own class, if also want to use len (myObj), then write yourself a __len __ () method:
 
>>> class myDog (Object): 
...      DEF  __len__ (Self): 
. ..          return 100 
...
 >>> Dog = myDog ()
 >>> len (Dog)
 100

2) hasattr: detecting the presence of properties

>>> class the MyObject (Object): 
...      DEF  the __init__ (Self): 
... self.x =. 9 
...      DEF Power (Self): 
...          return self.x * self.x 
...
 > obj = >> the MyObject ()
 # --------------------------- 
>>> the hasattr (obj, ' X ' ) # have attributes' x 'it? 
True
 >>> obj.x
 9 
>>> hasattr (obj, ' the y- ' ) # have attributes 'y' do? 
False

3)getattr和setattr

Setattr >>> (obj, ' the y- ' , 19) # set a property 'y' 
>>> hasattr (obj, ' the y- ' ) # have attributes 'y' do? 
True
 >>> getattr (obj, ' the y- ' ) # get property 'the y-' 
19 
>>> obj.y # get the properties 'the y-' 
19 
# If you try to acquire the property does not exist, an error will be thrown AttributeError: >> > getattr (obj, ' Z ' ) # get property 'Z' Traceback (MOST Recent Last Call): File " <stdin> AttributeError: ' the MyObject ' Object attribute has NO ' Z ' # may pass a default parameter, if the attribute does not exist, it returns a default value: >>> getattr (obj, ' Z ' , 404) # get property 'z', If not, return the default value 404 for 404 # also ways to get objects: >>> hasattr (obj, ' Power ' ) # have attributes 'power' it? True >>> getattr (obj, ' Power ' ) # get property 'Power' <Method MyObject.power of bound < __main__ .MyObject Object AT 0x10077a6a0 >> Power ' ) # get property' power 'and assigned to the variable Fn >>> Fn # Fn point obj.power <Method MyObject.power of bound < __main__ .MyObject Object AT 0x10077a6a0 >> >>> fn () # call fn ( ) calling obj.power () is the same as 81

 

3. @propertydecorator

One way to become responsible for the property called

before use

class Student(object):

    def get_score(self):
         return self._score

    def set_score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value

#----------------------
>>> s = Student()
>>> s.set_score(60) # ok!
>>> s.get_score()
60
>>> s.set_score(9999)
Traceback (most recent call last):
  ...
ValueError: score must between 0 ~ 100!

After use

(Only defines getter methods defined setter method is not a read-only property, the following example is a read-only attribute age, Birth and score are read-write property)

class Student(object):

    @property
    def age(self):
        return 2015 - self._birth

    @property
    def birth(self):
        return self._birth

    @birth.setter
    def birth(self, value):
        self._birth = value

    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value
    
#----------------------
>>> s = Student()
>>> s.score = 60 # OK,实际转化为s.set_score(60)
>>> s.score # OK,实际转化为s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
  ...
ValueError: score must between 0 ~ 100!

 

4. Multiple Inheritance

  

#设计类
class Animal(object):
    pass

# 大类:
class Mammal(Animal):
    pass

class Bird(Animal):
    pass

# 各种动物:
#class Dog(Mammal):
    #pass

class Dog(Mammal, Runnable):
    pass

#class Bat(Mammal): 
  #pass 

class Bat(Mammal, Flyable):
    pass

#class Parrot(Bird): 
  #pass 

#class Ostrich(Bird): 
  #pass 

#跑/飞类 

class Runnable(object): 
 
  def run(self): 
    print('Running...') 

class Flyable(object): 
    def fly(self): 
            print('Flying...')
            

 

MixIn

  A class to increase the number of functions, so that in the design category, we give priority to multiple inheritance by a combination of functions of multiple MixIn, rather than the design of complex multi-level inheritance.

 

Guess you like

Origin www.cnblogs.com/jpga/p/12581223.html