Python Object-oriented tips

Source: Internet
Author: User

(i), Python duck type

Python is very different as dynamic language inheritance and polymorphism and static language (like Java), for example, in Java, a method, if the passed parameter is a Animal type, then the incoming object must be a Animal type or its subclass, otherwise, the method cannot be called run() . For Python, the incoming type is not necessarily required Animal . We just have to ensure that the incoming object has a run() method, which is the "duck type" in dynamic language, does not emphasize strict inheritance, only need to "look like a duck, even if you are a swan",

So if your object has that method, it's the way Python is oriented to process or function-oriented in the Object!

# coding=utf-8classAnimal (Object): def run (self): print ('Look, there's an animal running.')classDog (Animal): def run (self): print ('Look, it's a dog running.') def eat (self): print ('The dog is eating.')classCar (Object): def run (self): print ('the car started ... ') def gogogo (animal): Animal.run () # animal.eat () GoGoGo (Dog ()) Print ("-- Test Duck type--") GoGoGo (Car ())

(ii), access rights in Python

1). In Python, the variable name starts with a double underscore (__xxx__) and ends with a double underscore, which is a special variable that can be accessed directly, not a private variable, not a property name of the object.'__xxx__'this format;2). To'_xx'The instance variable at the beginning is accessible, but it just tells us that it can be accessed, but as a private variable, not to be accessed arbitrarily;3). The variable name of the instance if the'__xx'Start, this becomes a private variable (Private), can only be accessed internally, "External cannot be accessed directly," and cannot be accessed directly'__xx'is because the Python interpreter'__xx'The variable is changed into'_object__xx'(This is important and can help to understand a lot of problems), so you can still'_object__xx'To access'__xx'Variable.

(iii), pending ING

Python Object-oriented tips

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.