zoukankan      html  css  js  c++  java
  • 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>>

      

  • 相关阅读:
    山东省第三届ACM省赛The Best Seat in ACM Contest
    Rescue The Princess(2013年山东省第四届ACM大学生程序设计竞赛A题)
    自定义颜色(UIColor)
    调用主程序的委托
    设置View的背景颜色
    基本控件_UIImageView
    CGRect
    屏幕尺寸
    UIScrollView 原理
    设置将警告当做Error来对待
  • 原文地址:https://www.cnblogs.com/backinfile/p/5949066.html
Copyright © 2011-2022 走看看