python的self和c++的this

python的self和c++的this
  • 最近在准备秋招,同时复习python和c++,在面对对象编程时发现两个语言的一些知识点有一些相似性,因此想把两个语言的共同性用自己的理解讲出来。
python的self

很多时候我们定义一个类时会发现类里面的成员函数参数前都会有一个self,但是当我们实例化对象后调用这个函数,却只用传入一个实参,直接跳过了self,如下例子,这是为什么呢?self到底是什么?

class Cat:
    def say(self, name):
        print(name)
        

if __name__ == '__main__':
    c = Cat()
    c.say("666")

下面我们来深入的探究一下self

class Cat:
    def say(self, name):
        print(name)


if __name__ == '__main__':
    c = Cat()
    print(Cat.say)
    print(c.say)
'''
<function Cat.say at 0x000002553A3A8310>
<bound method Cat.say of <__main__.Cat object at 0x000002553A3A5A30>>
'''

我们在调用发现,这个self占用一个形参位置的情况只有在你实例化一个对象后调用此成员函数才会出现这种情况,并且上面这个例子我们可以发现用普通类调用say和实例化对象类,打印出的东西时不一样的,对象调用函数时一个bound method 即说明这是一个绑定了一个对象的方法。

我们再看这个self到底是什么?

class Cat:
    def say(self, name):
        print(name)
        print(self)

if __name__ == '__main__':
    c = Cat()
    print(c)
    c.say("666")
'''
<__main__.Cat object at 0x0000024A6C6B5A30>
666
<__main__.Cat object at 0x0000024A6C6B5A30>
'''

我们在这个例子,直接打印实例化的对象,并且在成员函数中打印了self,发现打印出来的东西是一样的,说明python在调用类方法的时候,函数的第一个参数默认会指向你实例化的对象,之后才是你传入的实参,因此这个self相当于是一个默认的占位符,而这个self这个形参的名字是随便取的。

至于这个self到底有什么用呢?用我的理解就是可以在一个类中进行变量共享

class Cat:
    name1 = "777"
    def say(self, name):
        print(name)
        self.name1 = 999
        print(self)
    def say2(self):
        print(self.name1)
        print(self.name)

if __name__ == '__main__':
    c = Cat()
    c.name = "666"
    print(c.__dict__)
    c.say("666")
    c.say2()
    
 '''
 {'name': '666'}
666
<__main__.Cat object at 0x000001EB6B265A30>
999
666
 '''

例如我们通过上面这个例子可以发现我们可以在类的任意地方用self这个桥梁进行变量的共享,这个变量的数值是存在__dict__这个字典里面的,这样的话我们可以在类的任意成员函数中通过self.xxx的方式拿到数据

c++的this指针

this指针指向被调用的成员函数所属的对象

例子如下:

#include <iostream>
using namespace std;

class Cat{
public:
    int a;
    void print_object()
    {
        cout << this;
    }
};

int main(){

    Cat cat;
    cout << &cat << endl;
    cat.print_object();
	return 0;
}
/*
0x2acc5ffadc
0x2acc5ffadc
*/

我们分别在main函数和成员函数中打印对象地址和this指针,可以看到this指针的值和对象的地址是相同的,因此c++的this指针其实和python的self有点类似,但是不同的是c++的this指针是一个关键字,python的self是约定俗成的。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Every so often a book comes along that makes you ask yourself, "Gee, when was the last time I had my eyes checked?" David M. Beazley's Python: Essential Reference is just such a book. Condensing thousands of pages of Python online documentation into a compact 319-page softcover, Beazley and his editors used the old-college trick (often performed in reverse) of dickering with the font size to meet a putative page-limit requirement. The result is a truly condensed product fit for the occularly well-adjusted (nota bene). Beazley's subject is Python, a full-featured, freely-redistributable, POSIX-compliant (platforms include Linux, Unix, Macintosh, and Windows) scripting language that is based on object-oriented design principles. As advertised, Beazley's source release (1.5.2) is available from an unfortunately slow server at www.python.org. The installation under Linux (Redhat 5.2) proceeded without incident. Beazley holds true to his catalogic purpose: fully 230 pages are formatted as technical appendices and indices covering the standard litany: built-in function syntax, database features, OS-level interfaces, Internet interfaces, and compiling/profiling/debugging. All references are fully annotated and illustrated with example source code that runs from a couple of lines to a couple of pages. In lock step with competing scripting languages, Python is extensible and embeddable in C and C++, and with blitzkrieg efficiency, Beazley summarizes these crucial practical issues in the final 30 pages. Python users who are tired of chasing questions through hyperlinked online documents will benefit from the expansive random-access index. Python the book captures the orderliness of Python the language. Beazley begins with an 86-page précis of Python in the fashion of Kernighan and Ritchie: too brief for a newbie tutorial but enough to propel old hands into a scripting language that aspires to the elegance of a compiled language. Indeed, it is a byte-compiling language. The line bytecode=compile("some_python_script",'','exec')) creates 'bytecode' as a token executed by exec bytecode. But a five-minute investigation through Beazley's book does not describe how 'bytecode' can be written into a separate executable file. If writing the byte-compiled code to a file is not possible, Python suffers from the limitations of other scripting languages: the executable is the source and cannot be hidden from the user, at least not without some difficulty. Despite its extensibility, embeddability, and pleasing architecture, Python is like other scripting languages: appropriate for solving small nonproprietary problems. Those familiar with more established scriptors like Perl may ask, "Why Python?" Unlike Perl, Python is a product of the fully object-oriented (OO) era, and its constructs reflect design principles that aspire beyond keystroke shortcuts of the succinct-but-often-arcane Perl. Python creator Guido van Rossum cleansed Perl's idiosyncracies and objectified basic data structure, data manipulations, and I/O. With Python, OO is so intrinsic that learning Python is equivalent to learning OO. The same cannot be said of Perl. Unfortunately, comparisons with other languages are missing from Beazley's book. Van Rossum, in an embarrassingly self-serving foreword, preemptively asserts that we readers need "neither evangelizing nor proselytizing"--after all, we already own the book--but we do need galvanizing and we don't find it. Specifically, we need a response to the oft-repeated wisdom that new computer languages are only worth learning if they teach us to organize our thinking along new lines. Scripting languages, however, are for quick and dirty projects: quick to write, easy to hack, and ultimately disposable. The essential tension created by van Rossum and friends is between the elegance of object-oriented principles and the utility of a quick-hacked script. Sadly, the tension remains unresolved in Beazley's reference. There is little to convince us that Python has earned its place in the firmament by changing our thinking. But Beazley has given us much to get us going if we have already taken the leap of faith. --Peter Leopold --This text refers to an out of print or unavailable edition of this title. From Library Journal Though Python is a relatively new programming language, it has quite a significant audience owing to its sensible syntax. An active user of Python since 1996, Beazley provides ample information on the fundamentals of versions 2.0 and 2.1, including syntax, functions, operators, classes, and libraries. This is first and foremost a reference, so he avoids lengthy discussions of Python's superiority. Peppered with good code samples and featuring a companion web site with more extensive pieces, this title should be on hand in larger libraries. Copyright 2001 Reed Business Information, Inc.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值