一个简单的python的类的例子:
#encoding = utf-8
class Person(object):
def __init__(self, name, age):
#这儿self.name和self.age都是object的attributes
self.name = name
self.age = age
print '%s has been born in' %(self.name)
p1 = Person('Johnny', 2001)
p2 = Person('Mary', 1987)
这时候如果打印p1而不是p1.name,只会打印出p1对象(内存地址)
怎么打印object的data?答案是转换成str
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
print '%s has been born' %(self.name)
def __str__(self):
#这个时候class的调用会返回str
return '%s is %s years old' %(self.name, self.age)
p1 = Person('Johnny', 20)
p2 = Person('Mary', 27)
print p1
print p2
添加一个 del method
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
print '%s has been born' %(self.name)
def __str__(self):
#这个时候class的调用会返回str
return '%s is %s years old' %(self.name, self.age)
def __del__(self):
#添加一个del method
print '%s is deleted :(' %(self.name)
p1 = Person('Johnny', 20)
p2 = Person('Mary', 27)
print p1
print p2
del(p1)
del(p2)
class variable
class Person(object):
population = 0 #注意不在__str__里面,也没有self在前面
def __init__(self, name, age):
self.name = name #self定义的object variable,是object的attributes
self.age = age
print '%s has been born' %(self.name)
Person.population += 1 #注意Person.,因为这是class variable
def __str__(self):
#这个时候class的调用会返回str
return '%s is %s years old' %(self.name, self.age)
def __del__(self):
#添加一个del method
print '%s is deleted :(' %(self.name)
Person.population -= 1 #注意Person.,因为这是class variable
p1 = Person('Johnny', 20)
print Person.population
p2 = Person('Mary', 27)
print Person.population
print p1
print p2
del(p1)
print Person.population
del(p2)
print Person.population
class method or static method(好像python2.7不能运行通过,只能python3运行)
class Person:
population = 0 #注意不在__str__里面,也没有self在前面
def __init__(self, name, age):
self.name = name #self定义的object variable,是object的attributes
self.age = age
Person.population += 1 #注意Person.,因为这是class variable
def __str__(self):
#这个时候class的调用会返回str
return '%s is %s years old' %(self.name, self.age)
def __del__(self):
#添加一个del method
Person.population -= 1 #注意Person.,因为这是class variable
def totalPop(): #注意括号里面没有self,所以跟object不相连
print('There are {0} people in the world'.format(Person.population))
p1 = Person('Johnny', 20)
p2 = Person('Mary', 27)
Person.totalPop() #这样没问题,因为是class method
p1.totalPop() #会报错,因为不是object p1的method
reference: https://www.youtube.com/watch?v=gGMwx9JHpWc