python里的self用法【Python教程】,python
作者:搜教程发布时间:2019-11-27分类:Python教程浏览:54评论:0
导读:self的用法1.自身指的是实例自身(Instance)(引荐进修:Python视频教程)2.由于"自身"这个词,都是相对而言的"别的"说的,指的是类class,...
self的用法
1.自身 指的是实例自身(Instance)(引荐进修:Python视频教程)
2.由于"自身"这个词,都是相对而言的"别的"说的,指的是类class,和别的变量,比方局部变量,全局变量
此处的self,是个对象(Object),是当前类的实例。
Python中为何要有self
在类的代码(函数)中,须要接见当前的实例中的变量和函数的,即接见(实例)Instance中的
对应的变量(属性,property):Instance.ProperyNam,去读取之前的值和写入的值
(2)挪用对应的函数(function):Instance.function(),即实行对应的行动
而须要接见实例的变量和挪用实例的函数,固然须要对应的实例Instance对象自身
而Python中就划定好了,函数的第一个参数,就必须是实例对象自身,而且,发起,把其名写为self
#! usr/bin/python3.7 # -*- coding:utf-8 -*- """ class Person(object): def __init__(self, name, lang, website): self.name = name self.lang = lang self.website = website print('self', self) print('type of self', type(self)) class Dog(object): def __init__(self, name, dog_type): self.name = name self.dog_type = dog_type # def sayhi(): # print("hello I am dog, my name is ",self.name) def sayhi(self): print("hello ,I am dog, my name is ",self.name) if __name__ == '__main__': p = Person('xiaoliang', 'hanyu', 'www.mutual-helper.com') d = Dog('Caty', 'Firce') """当顺序运行时,会报错,takes 0 positional arguments but 1 was given 这是由于这个函数不须要参数,然则函数却被通报了一个参数,但是我们挪用sayhi()函数的时刻, 并没有写参数。为何会涌现如许的参数Error 这是由于"每个相干联的要领挪用都自动通报实参self,它是一个指向实例自身的援用__init__中的 参数self会自动通报给sayhi(),而sayhi()在定义的时刻没有形参,就会报错。 """ d.sayhi() # d.sayhi(self),也会报错
更多Python相干技术文章,请接见Python教程栏目举行进修!
以上就是python里的self用法的细致内容,更多请关注ki4网别的相干文章!
标签:python
相关推荐
- python数据类型有哪几种?_Python教程,python
- python针对Excel表格的操作_Python教程,python,excel
- 实例解析Python单元测试及unittest框架用法_Python教程,python,单元测试,unittest框架
- Python如何使用xlrd实现读取合并单元格_Python教程,python,xlrd
- 手把手教你在python中如何使用while True语句_Python教程,python,while true
- 给大家分享一下日常学习python的心得(详解)_Python教程,python
- python如何另起一行?_Python教程,python
- python是一种跨平台、开源、免费的高级动态编程语言,对么_Python教程,python,跨平台,开源,免费,编程语言
- 关于python装饰器的详细介绍_Python教程,python,装饰器
- 推荐几个适合小白学习Python的免费网站_Python教程,python,网站
你 发表评论:
欢迎- Python教程排行
-
- 1python数据类型有哪几种?_Python教程,python
- 2pycharm中文版界面如何设置?_Python教程,pycharm
- 3python如何批量处理excel数据?_Python教程,python,excel数据
- 4python针对Excel表格的操作_Python教程,python,excel
- 5在python中导入其它函数库的关键字是什么_Python教程,python,函数库,关键字
- 6python爬虫代码示例分享_Python教程,python,爬虫,代码,示例
- 7Python控制Excel实现自动化办公_Python教程,python,excel,自动化
- 8手把手教你在python中如何使用while True语句_Python教程,python,while true
- 9python如何进行进制转换_Python教程,python,进制转换
- 最新文章
- 广而告之