在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.