Python object-oriented programming (class and instance, data encapsulation, inheritance, polymorphism, type (), isinstance ()) - 5

A class and instance

1. The definition of property-related issues

  • Class names are usually capitalized
  • Form is defined as class Student(object):, Student behind the brackets indicate which class inheritance, if no suitable is to use the object.
  • Some believe we must bind class attributes, by defining a __init__method, the first parameter of the method is always self, because the self is the point to create instances of itself.
  • With the __init__method, create an instance in time, you can not pass a null parameter, you must pass the __init__parameter matching method, but do not need to pass self, Python interpreter himself will pass in an instance variable.
  • And compared to normal function, only a little different in function defined in the class, is the first argument is always an instance variable self, and when you call, do not pass this parameter.

2. Data Package

  • By accessing the class defined inside the class property function, encapsulated data.
  • A method is a function instance is bound, different from normal function, the method may directly access the data instance.
  • And static different languages, Python allows any data variable bindings for instance, that is to say, for two instance variables, although they are different instances of the same class, but the variable names have may be different.

Second, limit access

  1. If you want external access inside the property is not to be put before the name of the property plus two underscores __, in Python, the instance variable names if the __beginning, it becomes a private variable (private), can only access the internal , not external access.
  2. If you want to access external code, you can increase to Student class get_nameand get_scoremethod for external access.
  3. If you have to modify the score, you can increase set_namemethod.
  4. Sometimes, you will see an instance variable names begin with an underscore, for example _name, such an instance variable names are available, but in accordance with the provisions are treated as private variables.
  5. Beginning with a double underscore instance variables are not necessarily not be accessed from outside it? In fact, no. Can not directly access __namebecause the Python interpreter outside the __namevariable changed _Student__name, so, can still _Student__nameaccess the __namevariable
  6. But it is strongly recommended that you do not do it, because different versions of the Python interpreter may put __name into a different variable names. Overall it is, Python does not have any mechanism to stop you from doing bad things, all thanks to the conscious.
class Student(object):
    def __init__(self, name, gender):
        self.__name = name
        self.__gender = gender
    
    def get_name(self):
        return self.__name

    def get_gender(self):
        return self.__gender

    def set_gender(self, gender):
        self.__gender = gender


bart = Student('Bart', 'male')
if bart.get_gender() != 'male':
    print('测试失败!')
else:
    bart.set_gender('female')
    if bart.get_gender() != 'female':
        print('测试失败!')
    else:
        print('测试成功!')    

Third, inheritance, and polymorphism

  1. Inherited the biggest advantage is that, for the sub-category, access to the full functionality of the parent class.
  2. Of course, you can also increase the subclass methods, such as Dog class.
  3. When the parent class and subclass are present in the same way for subclasses override methods of the parent class, the code is running, there is always a subclass method calls, so that we get the benefit of another inheritance:多态
  4. So, in the hierarchy, if the data type is an instance of a subclass of the type of data that it can also be seen as a parent. However, the reverse will not work
  5. Multi-state benefits, the caller just calls, regardless of the details, this is the famous 开闭原则: open for extension: allow new Animal subclass; closed for modification: Animal depend not need to change the type of run_twice () and other functions.
  6. Static vs dynamic languages language for statically typed languages (such as Java), if the need to pass Animal type, the incoming object must be of type Animal or its subclasses, otherwise, you can not call the run () method; for Python such a dynamic language, you do not necessarily need to pass in Animal type. We just need to ensure that incoming object has a run () method on it.

Fourth, get the object information

  1. Use type()function can be used to determine the type of the object. Class returns the corresponding type.
  2. To determine if an object is a function, you can use typesthe constants defined in module
  3. Use isinstance()Analyzing Class type. And also determines whether or not a variable of a certain type,isinstance([1, 2, 3], (list, tuple)
  4. To get an object's properties and methods, you can use dir()the function. With getattr(), , setattr(), hasattr()we can directly operate an object's state.
>>> class MyObject(object):
...     def __init__(self):  
...         self.x = 9
...     def power(self):
...         return self.x * self.x
... 
>>> obj = MyObject()
>>> hasattr(obj, 'x')
True
>>> obj.x
9
>>> hasattr(obj, 'y')
False
>>> setattr(obj, 'y', 19)
>>> hasattr(obj, 'y')
True
>>> getattr(obj, 'y')
19
>>> obj.y
19
>>> getattr(obj, 'z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyObject' object has no attribute 'z'
>>> getattr(obj, 'z', 404)
404
>>> hasattr(obj, 'power')
True
>>> getattr(obj, 'power')
<bound method MyObject.power of <__main__.MyObject object at 0x00000224FC11FF60>>
>>> fn = getattr(obj, 'power') 
>>> fn
<bound method MyObject.power of <__main__.MyObject object at 0x00000224FC11FF60>>
>>> fn()
81

V. instance attributes and class attributes

  1. Examples of a method of binding property is variable by way of example or by selfvariable.
  2. If the Studentclass itself needs to bind a property can define attributes directly in the class, this property is the class attribute, in the final Studentclass for all.
  3. In the preparation of procedures, do not for instance attributes and class attributes with the same name, because the instance property of the same name will shield the class attribute, but when you delete the instance attribute, and then use the same name, access to the It will be the class attribute

Guess you like

Origin www.cnblogs.com/tsruixi/p/12595147.html
Recommended