程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The understanding of the self and class in Python

編輯:Python

In order to clarify what self is, we first need to understand the relationship between instances and classes.

People are a type of people. People have attributes such as name, height, and weight. These attributes are different for different people. In addition, people have many methods (functions), such as thinking, running, sleeping, etc..

class Person:def __init__(self, name):self.name = name # define the properties of the classdef think(self): # self is actually an ordinary parameter of the class function think, which represents the called object, and the specific value of the parameter is our instance objectprint("{} is thinking".format(self.name))

Specific to each person, such as yourself, each specific person around you is an instance object of "human".Instances inherit all properties and methods of the class, for example:

xiaoming = Person("xiaoming")

We constructed a person called "xiaoming", which is an instance object of the Person class. We define a think method for the Person class, but it needs a parameter. We can pass the instance object of xiaoming.

>>>Person.think(xiaoming)xiaoming is thinking

So, the self here is actually just an ordinary parameter of the class function think, which represents the called object, and the specific value is our instance object, so why is it called self?In fact, this is a convention.


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved