Home  >  Article  >  Backend Development  >  How to use self in python

How to use self in python

(*-*)浩
(*-*)浩Original
2019-07-04 10:17:549048browse

Usage of self

How to use self in python

1. Self refers to the instance itself (Instance) (recommended learning: Python video tutorial)

2. Since the word "self" refers to "other" in relative terms, it refers to the class, and other variables, such as local variables and global variables

self here, It is an object (Object), an instance of the current class.

Why is there self in Python

In the class code (function), you need to access the variables and functions in the current instance, that is, access (instance) The variable (property) corresponding to

in Instance: Instance.ProperyNam, to read the previous value and the written value

(2) Call the corresponding function: Instance.function(), that is, to perform the corresponding action

and need to access the variables of the instance and call the function of the instance, of course the corresponding instance Instance object itself is required

It is stipulated in Python that the first parameter of the function must be the instance object itself, and it is recommended to write its name as 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),也会报错

More Python related technical articles , please visit the Python Tutorial column to learn!

The above is the detailed content of How to use self in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn