python方法中的self

  前几天在写一个c作业时,突发奇想,在结构体中加入函数指针,

  像这样:

struct People {
    int _age;
    int (*age)();
}people;

  这样调用时就可以 people.age() 

  这是可行的,因为在c中,  foo() 和 (&foo)() 是一样的,

 也就是说 people.age() 和 (*(people.age))() 是一样的。

  若要求有多个People对象,就要把结构体当做参数:

struct People {
  
int _age;
  void (*init)(struct People
*);
  int (*age)(struct People *); };
int People_age(struct People *p) {
  return p->_age;
}

void People_init(struct People *p, int age) {
  p->_age = age;
  p->age = &People_age;
}

  使用时,

struct People people;
people.init = &People_init;
people.init(people, 20);
age = people.age(people);

  仔细想来,这种在方法中传递对象自身的方式,神似python。

class cls:
    def __init__(self, age):
        self._age = age
    def age(self):
        return self._age

c = cls(20);
age = c.age()

  python把age函数绑定到对像cls的实例c上,调用时默认把c作为self传入age

  这可以在ipython中看出:

In [6]: cls.age
Out[6]: <unbound method cls.age>

In [7]: c = cls(20)

In [8]: c.age
Out[8]: <bound method cls.age of <__main__.cls instance at 0x7f49df7da710>>

  

原文地址:https://www.cnblogs.com/backinfile/p/5949066.html