博客
关于我
python3面向对象--python3中类方法的特殊性与self
阅读量:611 次
发布时间:2019-03-12

本文共 547 字,大约阅读时间需要 1 分钟。

类方法的特殊性

在面向对象编程的语言中,类方法的定义通常遵循特定的规则。而在Python中,这些规则与其他语言有所不同,值得特别关注。

类方法的定义在Python中必须包含参数self,并且它是参数列表中的第一个参数。self表示类实例,与Java中的this概念相似。尽管self不是限定关键字,但在Python中习惯上统一使用self作为参数名。

例如,在类Persion中:

class Persion:    def sayHello(self):        print("hello world!")    persison2 = Persion()    persion2.sayHello()  # 正确调用方式

如果方法定义不包含self参数,即使在调用时传递参数,也会导致错误:

def sayHello():    print("hello world!")persion2 = Persion()persion2.sayHello()  # 会抛出TypeError:sayHello() takes 0 positional arguments but 1 was given

因此,在定义类方法时,必须将self作为第一个参数,正确地将实例作为方法的第一参数传递。

转载地址:http://hbtxz.baihongyu.com/

你可能感兴趣的文章
Nginx
查看>>
nginx + etcd 动态负载均衡实践(一)—— 组件介绍
查看>>
nginx + etcd 动态负载均衡实践(三)—— 基于nginx-upsync-module实现
查看>>
nginx + etcd 动态负载均衡实践(二)—— 组件安装
查看>>
nginx + etcd 动态负载均衡实践(四)—— 基于confd实现
查看>>
Nginx + Spring Boot 实现负载均衡
查看>>
Nginx + Tomcat + SpringBoot 部署项目
查看>>
Nginx + uWSGI + Flask + Vhost
查看>>
Nginx - Header详解
查看>>
nginx - thinkphp 如何实现url的rewrite
查看>>
Nginx - 反向代理、负载均衡、动静分离、底层原理(案例实战分析)
查看>>
Nginx - 反向代理与负载均衡
查看>>
nginx 1.24.0 安装nginx最新稳定版
查看>>
nginx 301 永久重定向
查看>>
nginx connect 模块安装以及配置
查看>>
nginx css,js合并插件,淘宝nginx合并js,css插件
查看>>
Nginx gateway集群和动态网关
查看>>
nginx http配置说明,逐渐完善。
查看>>
Nginx keepalived一主一从高可用,手把手带你一步一步配置!
查看>>
Nginx Location配置总结
查看>>