在Python中类是对某个对象的定义,它包含有关对象动作方式的信息,包括它的名称、方法、属性和事件,下面文章可以进一步的学习和了解关于Python类的问题,类这个问题大大的提高了变量的数据。

对象可以使用普通的属于对象的变量存储数据。属于一个对象或Python类的变量被称为域。对象也可以使用属于类的函数来具有功能,这样的函数被称为类的方法。域和方法可以合称为类的属性。域有两种类型--属于每个实例(对象)的方法称为实例变量;属于类本身的称为类变量。
类的方法和普通的函数只有一个特别的区别--他们必须有一个额外的***个参数名称,但是在调用方法的时候你不为这个参数赋值,python会提供这个值。这个特别的变量指对象本身,按照惯例它的名称为self。
类与对象的方法可以看一个例子来理解:
- class Person:
 - population=0
 - def __init__(self,name):
 - self.name=name
 - Person.population+=1
 - def __del__(self):
 - Person.population -=1
 - if Person.population==0:
 - print("i am the last one")
 - else:
 - print("There are still %d people left."%Person.population)
 - def sayHi(self):
 - print("hi my name is %s"%self.name)
 - def howMany(self):
 - if Person.population==1:
 - print("i am the only person here")
 - else:
 - print("we have %d persons here."%Person.population)
 - s=Person("jlsme")
 - s.sayHi()
 - s.howMany()
 - k=Person("kalam")
 - k.sayHi()
 - k.howMany()
 - s.sayHi()
 - s.howMany()
 - 输出:
 - hi my name is jlsme
 - i am the only person here
 - hi my name is kalam
 - we have 2 persons here.
 - hi my name is jlsme
 - we have 2 persons here.
 
population属于Python类,因此是一个Python类的变量。name变量属于对象(它使用self赋值)因此是对象的变量。 观察可以发现__init__方法用一个名字来初始化Person实例。在这个方法中,我们让population增加1,这是因为我们增加了一个人。
同样可以发现,self.name的值根据每个对象指定,这表明了它作为对象的变量的本质。 记住,你只能使用self变量来参考同一个对象的变量和方法。这被称为 属性参考 。
Copyright © 2009-2022 www.wtcwzsj.com 青羊区广皓图文设计工作室(个体工商户) 版权所有 蜀ICP备19037934号