开发者

Different ways to reference yourself?

开发者 https://www.devze.com 2023-01-15 22:23 出处:网络
The handle to yourself is called different things in OOP languages. The few I\'ve come across so far:

The handle to yourself is called different things in OOP languages. The few I've come across so far:

  • this (e.g. Java, C#)
  • Me (e.g. VB, vba)
  • self (e.g. Python)

Anyone know any ot开发者_高级运维hers?


In Python, it is just a convention that the zeroth argument is called self. What matters is the position. Anything will do, so you could use i or anything else:

class Foo:
  def bar ( i ):
    print i


The search for self...

Most often it's nothing at all. For instance, usually "x" will refer to this.x if no local x variable exists.


In Perl, a reference to itself is never implicit.

sub work {
    my($self) = @_;
    sleep();         # Don't do this
    $self->sleep();  # Correct usage
}

source: "Writing serious Perl - The absolute minimum you need to know"


In multiple-dispatch OO languages like Common Lisp (CLOS), Dylan or Slate, there is no single receiver object, and therefore no notion of self.


Smalltalk also uses self.


F# is similar to Python and Perl, in that you just supply your own name. Here's @Pete Kirkham's Python example in F#:

type Foo =
  member i.bar = printfn "%O" i

Use it like so:

let x = new Foo()
x.bar
0

精彩评论

暂无评论...
验证码 换一张
取 消