Python contacts (3)

Source: Internet
Author: User
Tags gtk

 

Http://blog.csdn.net/idisposable

First eye on Boo Language

 

On the. NET platform, in addition to ironpython, Python also has another relative, boo.

But the boo language is not really the Implementation of The Python language, it just has the same coat as Python.

 

========================================================== ==============================

Below are my learning notes for reading booprimer ,:)

1. Like other language tutorials, booprimer starts with "Hello, world.

Print "Hello, world! "

Or

Print ("Hello, world ")

Is it the same as in Python? In Python 2.6 and earlier versions, print statement adopts the previous form. After Python 3.0, print has become a function. Boo supports two forms. I think it is also intended to be compatible with python.

We recommend that you use a macro (print "Hello, world! "), Which is different from the development direction in Python. Let's take a look at the compiled code (the code that is viewed by. Net reflector after compilation ).

(A) The compiled code of print "Hello, world" is:
Console. writeline ("Hello, world ")

(B) print ("Hello, world") compiled code:
Builtins. Print ("Hello, world ")

If you are interested in builtins. Print, you can check it by yourself.

2. String interpolation (string insertion)

String interpolation makes string formatting easy. Let's look at the example:

Toy = "kitty"
Print "Hello, $ {toy }"

Any valid boo expression can be inserted into the string. When a string is expanded, boo calculates the expression and then calls the tostring method of the expression result. You can write a few lines of simple code to verify this. The Code is as follows:

Class testobject:

Def tostring ():

Return "this is an instance of class testobject"

OBJ = testobject ()

S = "Result: $ {OBJ }"

3. All objects in boo are objects.

This does not need to be explained much. Boo and Python are the same-in their world, what are objects, built-in basic data types (such as integer, character, string), code segments, all interpreters are objects. Even the type itself is an object (it may be crazy if you have never touched Python/boo before ).

>>> OBJ as object
>>> Print OBJ = NULL
>>> True
>>>

In the above Code, the as keyword is used to explicitly specify the object type. This is also a difference between boo and Python-you can specify the object type to enhance security. In addition, there are 1.1 rules. Don't forget: Boo is not a real dynamic language, so the object type is fixed in its lifecycle.

4. Check the runtime type of the object (runtime type of an object)
Unlike python, because Boo is Based on. NET, its type system also uses the. NET Common Type System (CTS ).

The method for detecting objects is also the same as that of. net.

(A) obj. GetType ()

(B) typeof

However, I found that typeof is not useful at all. As follows:

 

>>> L = [1, 2, 3]
>>> Typeof (l)
Error: The name 'l' does not denote a valid type.
>>> T = L. GetType ()

Boo. Lang. List
>>> Typeof (t)
Error: The name 't'does not denote a valid type.
>>> Typeof (Boo. Lang. List)
>>> Boo. Lang. List
>>>

Typeof is too rigid compared with type () in Python.

 

5. builtin Functions)

Boo supports some built-in functions such as print, gets, prompt, join, MAP, array, matrix, iterator,
Shellp, Shell, shellm, enumerate, range, reversed, zip, Cat, etc.

 

6. User-Defined Functions

The syntax of the UDF in Boo is the same as that in Python. However, the definition of member functions is somewhat different from that of Python, which will be detailed in a series of articles in the future.

Here are some examples of user-defined functions:
Def Hello ():
Print "hello"

# This function specifies the return value type
Def Hello () as string:
Print "hello"

Def Hello (name ):
Print "Hello, $ {name }"

# This function specifies the parameter type
Def Hello (name as string ):
Print "Hello, $ {name }"

Specifying a type for parameters and return values improves program security. Boo can perform type checks on parameters and return values.

 

7. Overloading
Boo performs much better in function overloading than python. Let's look at a simple example.

Def Hello ():

Return "Hello, world! "

 

Def Hello (name as string ):

Return "Hello, $ {name }! "

 

Def Hello (Num as INT ):

Return "Hello, number $ {num }! "

 

Def Hello (name as string, other as string ):

Return "Hello, $ {name} and $ {Other }! "

 

8. variable parameters

Boo also supports variable parameters. E.g.

>>> Def test (* ARGs as (object )):
>>> Return args. Length
>>> Print test ("Hey", "there ")

2
>>> Print test (1, 2, 3, 4, 5)

5
>>> Print test ("test ")

1

 

>>> A = (7, 9, 8)
>>> Print test (*)

According to booprimer, the last test (* A) should return 3. However, an error occurs when boo 0.7.6 is used:

Error: The best overload for the method 'input27module. Test (* (object) 'is not compatibleThe argument list '(* (INT ))'.

 

9. Property and Field)

Boo distinguishes property from field, which is more comfortable for. Net programmers. You can also define properties through attribute in boo.

Class Cat:
[Property (name)] // This is an attribute. Read and Write the field _ name through its access
_ Name as string // This is a field and cannot be accessed from outside the class. You should use attributes to access it.

Check whether the following setter/getter is very similar to that in C?

Class Cat:

[Getter (name)]

_ Name = 'meowster'

[Setter (favoritefood)]

_ Favoritefood as string

 

Fluffy = CAT ()

Print fluffy. Name

Fluffy. favoritefood = 'broccol'

 

The above setter/getter is an implicit form. Let's take a look at the example of an explicit attribute.
Class Cat:
Name as string:
Get:
Return _ name
Set:
_ Name = Value
_ Name as string

9.1 pre-condition of property
Class Cat:

[Property (name, name is not null)]

_ Name as string

 

Fluffy = CAT ()

Fluffy. Name = NULL # setting a null value for the name attribute will cause an argumentexception exception.

I don't know if C # has similar features?

 

10. Class Modifiers
Public, protected, internal, protected internal, Private, abstract, final

"Public" is assumed if no modifier is specified

Boo learns from. Net to define a bunch of class modifiers, so that fine-grained access control can meet better security requirements.

11. Interface Support
This is an advantage of BOO over Python-the concept of interfaces supported at the language layer.

E.g.
Interface ifeline:
Def roar ()
Name:
Get
Set

12. Value Type and reference type

Like. net, all classes are reference types. The basic types are value types, such as int, long, double, bool, and byte. Value types always have values (cannot be set to null). They have default values. For example, the default value of the value type is 0.

 

13. class member Methods

Defining member methods is similar to the syntax of Python. The difference is that the self keyword is not required.

Class Cat:

Def roar ():

Print "Meow! "

Cat = CAT ()

Cat. Roar ()

 

14. constructor and destructor)

Class Cat:

Def Constructor ():

_ Name = "Whiskers"

Def destructor ():

Print "$ {_ name} is no more ..."

[Getter (name)]

_ Name as string

 

Cat = CAT ()

Print cat. Name

Because of the uncertainty of. net, your code cannot be called depending on the destructor. You may never know when it will be called.

 

15. Method Modifiers

Abstract: Abstract METHODS

Static: Static Method

Virtual, override-virtual method and method rewriting.

These are consistent with C #/. net.

 

16. Member visibility

Member visibility can be divided into several types: public, protected, provate

If no explicit declaration is made, all fields are protected by default, while methods, properties, and events are public by default.

 

17. Declare properties in the constructor)

This is a good language feature.

Class box:

Def Constructor ():

Pass

[Property (value)]

_ Value as object

 

Box = Box (value: 42)

Print box. Value

 

18. polymorphism and inheritance

Polymorphism and inheritance are two essential characteristics of object-oriented. There is nothing special about polymorphism and inheritance in the boo language, just like the C # language.

 

19. struct (structs)

The struct In the boo language is completely borrowed from. net. Struct is a value type. You can also define your own methods.

E.g.

Struct rectangle:

Def Constructor (w as int, H as INT ):

_ W = W

_ H = H

 

_ X As int

_ Y as int

Def area ():

Return _ w * _ H

 

20. namespace)

Compared with python, this is indeed a good thing-python can only use modules to deal with name conflicts.

20.1 declare namespace

Declare the namespace in the file header.

Namespace mynamespace

 

Class typeinthenamespace ():

Pass

 

What if you want to import another namespace? It is also very simple, just like C.

Import System

Import mynamespace

Import GTK from "GTK-sharp"// Quoted because there is a special character '-'.

 

21. enumerations)

There is nothing special. Let's look at the example.

Enum day:

Monday

Tuesday

Wednesday

Thursday

Friday

Saturday

Sunday

 

Class action:

[Property (day)]

_ Day as day

 

22. Exceptions)

Raising exceptions)

E.g.

Import System

Def execute (I as INT ):

If I <10:

Raise exception ("argument must be greater or equal to 10 .")

Print I

 

Caught exceptions)

There are three methods to capture exceptions: Try-Reboot T, try-ensure, and try-Restart T-ensure.

Let's take a look at the example below.

# Try-example t example

Import System

Try:

Print 1/0

Except t e as dividebyzeroexception:

Print "oops"

Print "doing other stuff"

 

# Try-ensure example

Import System

Try:

S = myclass

S. dosomethingbad ()

Ensure:

Print "this code will be executed, whether there is an error or not ."

The ensure here is equivalent to the finally of C.

 

Try-try t-ensure is the combination of the above two forms.

# Try-example T-ensure example

Import System

Try:

S = myclass

S. dosomethingbad ()

Failed t e as exception:

Print "problem! $ {E. Message }"

Ensure:

Print "this code will be executed, whether there is an error or not ."

 

23. Function calling and multithreading (functions as objects and multithreading)

In boo, everything is an object, so functions are no exception. Each function has three methods:

Invoke: Same as calling a function normally

Begininvoke: starts a working thread to run this function.

Endinvoke: Wait for the previously started thread to complete the function call and return the calculation result.

Because boo provides convenient asynchronous function calls, multi-threaded programming becomes very easy.

 

24. Generators)

Readers who have used Python must be familiar with generator.

Syntax definition of generator expressions:

<Expression> for <declarations> [as <type>] in <iterator> [if | unless <condition>]

E.g.

>>> List (X for X in range (5) // The simplest form

[0, 1, 2, 3, 4]

>>> List (X for X in range (5) if x % 2 = 0)

[0, 2, 4]

 

Generator method:

The gemerator method uses the yield keyword. This method looks like a common method but can be returned multiple times to the caller.

Is it hard to understand? Let's see the example.

Def testgenerator ():

I = 1

Yield I

For X in range (10 ):

I * = 2

Yield I

 

Print list (testgenerator ())

 

Generator is inherited from ienumerable, so it can be used with for... in.

 

25. Macro (macros)

Boo provides several macros to facilitate programming. But I have a question: do boo support user-defined Macros?

 

Print macro

We are already familiar with this. E.g.

Print "Hello there"

Print "hello", "there"

Print "first", "second", "third", "more", "More and more"

 

Assert macro

This is a child of Defensive Programming.

Assert true // always passes

Assert false, "message" // always fails

 

Using macro

Like using in C #, it provides a lifecycle Control for protected objects.

E.g.

Using W = streamwriter ("test.txt "):

W. writeline ("Hello there! ")

 

Lock macro

Like C #, lock macro is used to synchronize object access in multi-threaded environments.

E.g.

Lock database:

Database. Execute ("update messages set id = ID + 1 ")

Debug macro

Similar to print macro, the difference is that print is output to system. Console, while debug macro is output to system. Diagnostics. debug.

 

26.Duck typing

Maybe it is easiest to understand without translation ,:)

Definition: Duck typing is a humorous way of describing the type non-checking system. initially coined by Dave Thomas in the Ruby community, its premise is that (referring to a value) "If it walks like a duck, and talks like a duck, then it is a duck."

 

Even though Boo is a statically typed language, duck typing is a way to fake being a dynamic language. duck typing allows variables to be recognized at runtime, instead of compile time. though this can add a sense of simplicity, it does remove a large security barrier.

E.g.

D As duck

D = 5 // now d is an integer

Print d

D + = 100 // any integer operation allowed

D = "hello" // The idle Miscellaneous d is changed to the string type.

Print d

D = D. toupper () // you can perform any string operation.

Print d

 

========================================================== ========================================================== ======================================

So far is Boo's learning notes. Let's write more about it later.

 

Related connections:

1. Official boo http://boo.codehaus.org/Boo website

2. sharpdevelop http://www.icsharpcode.net/OpenSource/SD/ provides a boo IDE environment

3. ironpython introduction http://blog.csdn.net/IDisposable/archive/2008/10/08/3035790.aspx

Related Article

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.