Created: 2025-04-16 mié 00:06
Object
.1: "Hello world Program"
2: 'Hello World!' printNl !
1: factorial
2: "Answer the factorial of the receiver."
3:
4: self = 0 ifTrue: [^ 1].
5: self > 0 ifTrue: [^ self * (self - 1) factorial].
6: self error: 'Not valid for negative integers'
1: Transcript show: 10 factorial.
1: 10 timesRepeat: [
2: Transcript show:'hello'.
3: Transcript cr.
4: ].
1: 1 to: 10 do:[ :i |
2: Transcript show:i.
3: Transcript show:' '.
4: Transcript show:i sqt.
5: Transcript cr.
6: ].
1: #('a' 'b' 'c' ) do: [:each |
2: Transcript show: each.
3: Transcript cr.
4: ].
1: |myArray myOperation|
2:
3: myArray := #('a' 'b' 'c' ).
4: myOperation := [:each |
5: Transcript show: each.
6: Transcript cr.
7: ].
8: myArray do: myOperation.
#import <stdio.h>
[obj method:parameter];
Puedes encontrar más en la página de la wikipedia.
Declaración de una clase:
1: // class.h
2: @interface classname : superclassname { ... }
3: +classMethod1;
4: +(return_type) classMethod2;
5: +(return_type) classMethod3: (param1_type)parameter_varName;
6: -(return_type) instanceMethod: (param1_type)param1_varName
7: secondParam: (param2_type)param2_varName;
8: @end
Implementación:
1: #import "class.h"
2:
3: @implementation classname
4: +classMethod {
5: // implementation
6: }
7: -instanceMethod {
8: // implementation
9: }
10: @end
1: -(int)changeColorToRed:(float)red green:(float)green blue:(float)blue
2: [myColor changeColorToRed:5.0 green:2.0 blue:6.0];
1: MyObject * o = [[MyObject alloc] init];
2: ...
3: -(id) init {
4: self = [super init];
5: if (self) {...}
6: return self;
7: }
Creación de una clase:
1: public class Model {
2: private Map<Character, FeatureVector> features;
3: /// Default constructor
4: public Model() {
5: features = new HashMap<>();
6: }
7: ...
Herencia de clases:
1: package gtaligner;
2: import gtaligner.io.Messages;
3: import gtaligner.io.TextReader;
4: public class BWImage extends BufferedImage {
5: private int[] weights;
6: ....
Herencia de interfaz:
1: public interface Sortable {
2: public bool isLessThan (Sortable b);
3: }
4: public class Line implements Sortable {...}
1: using System.Windows;
2: namespace MyCalculatorv1
3: {
4: public partial class App : Application
5: {
6: }
7: }
1: using System;
2: using System.Windows;
3: using System.Windows.Controls;
4: namespace MyCalculatorv1 {
5: public partial class MainWindow : Window {
6: public MainWindow() {
7: InitializeComponent();
8: }
9: private void Button_Click_1(object sender, RoutedEventArgs e) {
10: Button b = (Button) sender;
11: tb.Text += b.Content.ToString();
12: }
13: private void Result_click(object sender, RoutedEventArgs e) {
14: try {
15: result();
16: }
17: catch (Exception exc) {
18: tb.Text = "Error!";
19: }
20: }
21: ...
1: using GLib;
2: class Droid {
3: public Droid (string n) {
4: name = n;
5: }
6: public string name {get; set;} // propiedad: variable+set+get todo-junto
7: }
8:
9: int main () {
10: Droid d = new Droid ("correo");
11:
12: stdout.printf("Nombre: %s\n", d.name);
13: return 0;
14: }
Haciendo uso de notación funcional:
1: // Sort lines
2: import std.stdio, std.array, std.algorithm;
3:
4: void main() {
5: stdin
6: .byLineCopy // No es necesario usar () en la llamada
7: .array // si no hay argumentos
8: .sort
9: .each!writeln;
10: }
Uso de clases:
1: import std.stdio;
2:
3: class Base {
4: protected int y = 8;
5: private int n = 9;
6: }
7:
8: class Derived : Base {
9: public int get_n () { return n; } // We can access 'n' 'cause Base and
10: // Derived are declared in the same file!
11: public int get_k () { return k; }
12:
13: private int k = 0;
14:
15: ~this () {
16: writeln ("~Derived.");
17: }
18: }
19:
20: void main () {
21: Derived d = new Derived;
22:
23: writeln (d.get_k);
24: }
self
.
Los objetos se crean con la notacion que ya conocemos de C++
:
1: myObject = myClass()
El constructor invoca el método especial __init__
:
1: def __init__(self):
2: self.data = [] # Obligatorio el uso de self
Debemos emplear self
para llamar a otros métodos de la clase:
1: class Bag:
2: def __init__(self):
3: self.data = []
4:
5: def add(self, x):
6: self.data.append(x)
7:
8: def addtwice(self, x):
9: self.add(x)
10: self.add(x)
Podemos declarar variables y métodos de clase :
class Complex:
count = 0
def onemore():
Complex.count += 1
def __init__(self, realpart = 0.0, imagpart = 0.0):
self.r = realpart
self.i = imagpart
Complex.onemore()
def rpart(this):
return this.r
x = Complex(3.0, -4.5)
x2 = Complex()
print ("x.r = ", x.rpart())
print ("x2.r = ", x2.rpart())
print ("Complex numbers created: ", Complex.count)
# -------------- Output: --------------------
x.r = 3.0 x2.r = 0.0 Complex numbers created: 2
Admite herencia simple:
class DerivedClassName(BaseClassName): ...
Y también múltiple:
class DerivedClassName(Base1, Base2,...,BaseN):...
.py
.Los módulos se importan con la sentencia import:
import name-of-module
Los símbolos importados de un módulo pertenecen al espacio de nombres de ese módulo:
1: # Fibonacci numbers module, file: fibmod.py
2: def fib(n): # write Fibonacci series up to n
3: a, b = 0, 1
4: while a < n:
5: print(a, end=' ')
6: a, b = b, a+b
7: print()
8: ....
9:
10: # Main Program, file: main.py
11: import fibmod
12: fibmod.fib(200)
Se puede hacer visible un símbolo de un módulo importado con la construcción:
1: from fibmod import fib
2: fib(120)
Se admite el uso del carácter '*' como comodín:
1: from fibmod import *
2: fib(120)
Se permite el renombrado:
1: from fibo import fib as fibonacci
2: fibonacci(120)
pdb
.