定义类/实例(Class)
# -*- coding: UTF-8 -*-
class pp():
'''Description'''
def __init__(self,name): #初始化函数
self.name = name
self.i ='cxly'
def fn(self):
if self.name.split(' ')[0] == 'Liu':
return 'f:L'
else:
return 'f:ooo'
def __str__(self):
return self.name
def flen(self):
return len(self.name)
p_len = property(flen) #custom a property
def __del__(self): #定义解构器,与__init__对应,可以没有
print 'i am finished'
nn=['Liu y','cui xiao','zhang san','Liu 2'] for i in nn: print pp(i).p_len
直接初始化类中的函数:
class test(object): """docstring for test""" def __init__(self, aa,c): self.aa = aa self.c = c self.i='ddd' test.t1(self) #初始化下面的t1,t2函数 test.t2(self) def t1(self): if self.aa>10: self.aa = str(self.aa) + 'aagreater' self.i='t1ddd' self.c='200' else: self.aa = str(self.aa) + 'aaless' return self.aa def t2(self): if self.i=='t1ddd': self.c='2000' return self.i,self.c else: return 'meiguolai' def __str__(self): return str(self.c) # tt= property(t1) # tt2=property(t2) m=test(100,20) print dir(m) print m #返回值为2000,不需要再调用t1,t2函数
获取某个类下的所有实例
#!/usr/bin/python # -*- coding: utf-8 -*- 'its a class test' __author__ = 'mm_obj' #定义名为Stu的类 class Stu(object): #define Stu property def __init__(self,name,age,gender): self.name=name self.age=age self.gender=gender #define Stu method age def p_stu_age(self): print '%s \'s age is:%d' % (self.name,self.age) #define Stu method name age gender def p_stu_ag(self): print '%s \'s age is:%d,gender is:%s' % (self.name,self.age,self.gender) def p_stu_name(self): print '%s' % (self.name) Lily=Stu('Lily',20,'female') Lucy=Stu('Lucy',25,'female') #Print Lily.p_stu_age() #print Lily.p_stu_ag() #Lily.age=26 #print Lily.p_stu_ag() #获取Stu类下的所有实例 import gc for obj in gc.get_objects(): if isinstance(obj,Stu): print obj.name
将方法定义为属性:
class people(): def __init__(self,name,age): self.name = name self.age = age def page(self): #定义方法page,获取用户年龄 return self.age aage = property(page) #定义属性aage,将方法page定义为属性aage Lily = people('Lily',25) print dir(Lily) print Lily.aage 返回: ['__doc__', '__init__', '__module__', 'aage', 'age', 'name', 'page'] 25
定义私有函数:
class TT: def bb(self): print("its bb") self.__auth() #调用类中的私有函数 def __auth(self): #定义私有函数,只能在类内部被其他函数调用 print('its auth') def __del__(self): print('finished') t1=TT() t1.bb()
在Python中,变量名类似__xxx__的,也就是以双下划线开头,并且以双下划线结尾的,是特殊变量,特殊变量是可以直接访问的,不是private变量,所以,不能用__name__、__score__这样的变量名。
以一个下划线开头的实例变量名,比如_name,这样的实例变量外部是可以访问的,但是,按照约定俗成的规定,当看到这样的变量时,意思就是,“虽然我可以被访问,但是,请把我视为私有变量,不要随意访问”。
双下划线开头的实例变量是不是一定不能从外部访问呢?其实也不是。不能直接访问__name是因为Python解释器对外把__name变量改成了_Class__name,所以,仍然可以通过_Class__name来访问__name变量。但是强烈建议不这么干,因为不同版本的Python解释器可能会把__name改成不同的变量名
通过类方法修改实例的值:
class Student(object): def __init__(self,name,score): self.name=name self.__score=score def get_score(self): print('%s: score is %d.' %(self.name,self.__score)) def set_score(self, score): #设置实例的值,并对其进行判断是否合法 if 0 <= score <= 100: self.__score = score else: raise ValueError('bad score') s=Student('Lily',22) s.get_score() #返回Lily: score is 22. s.set_score(11) s.get_score() #Lily: score is 11.
类的继承:
class A(object): num = 0 #此为类变量 all =[] def __init__(self,name,age): self.name=name self.age=age self.tell() #初始化tell函数 def tell(self): A.num +=1 #调用类变量的属性值 A.all.append(self.name) print 'i am %s,my num is %d'%(self.name,A.num) #print 'i want to sutdy' class B(A): def __init__(self,name,age,course): super(B,self).__init__(name,age) #继承class A #A.__init__(self,name,age) #旧类的写法,等同于super(),不建议再继续使用 self.course=course lily=B('lyly',21,'math') #返回i am lyly,my num is 1 print lily.name,lily.course #返回lyly math lily.tell() #返回i am lyly,my num is 2 lily.tell() #返回i am lyly,my num is 3。tell方法调用一次,A.num即会+1,所以最好在init中进行初始化为好,如下:
print A.all,A.num #返回['lyly', 'lyly', 'lyly'] 3
#初始化类变量,计数 class A(object): num = 0 #此为类变量 all =[] def __init__(self,name,age): self.name=name self.age=age A.num +=1 A.all.append(self.name) def tell(self): print 'i am %s,my num is %d'%(self.name,A.num) class B(A): def __init__(self,name,age,course): super(B,self).__init__(name,age) #A.__init__(self,name,age) #旧类的写法,等同于super(),不建议再继续使用 self.course=course zhangsan=A('zhangsan',22) liming=B('liming',21,'english') lily=B('lyly',21,'math') #返回i am lyly,my num is 1 print lily.name,lily.course #返回lyly math lily.tell() #返回i am lyly,my num is 2 lily.tell() #返回i am lyly,my num is 3 print A.all,A.num #返回['zhangsan', 'liming', 'lyly'] 3
类变量与实例变量,初始化类函数:
class A(object): num = 0 #此为类变量 all =[] def __init__(self,name,age): self.name=name self.age=age self.tell() #初始化tell函数 def tell(self): A.num +=1 #调用类变量的属性值 A.all.append(self.name) print 'i am %s,my num is %d'%(self.name,A.num) #print 'i want to sutdy %s'%course zhangsan1 = A('zhangsan',20) zhangsan2 = A('zhangsan2',22) print A.all
#返回: #i am zhangsan,my num is 1 #i am zhangsan2,my num is 2 #['zhangsan', 'zhangsan2']