# -*- 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=''
else:
self.aa = str(self.aa) + 'aaless'
return self.aa def t2(self):
if self.i=='t1ddd':
self.c=''
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']

定义类/实例(Class)的更多相关文章

  1. python之定义类创建实例

    https://www.cnblogs.com/evablogs/p/6688938.html 类的定义 在Python中,类通过class关键字定义,类名以大写字母开头 1 2 >>&g ...

  2. python 类的定义 实例化 实例完后初始化

    先来看看 类的__init__, 类的__new__ , 元类的__new__的执行顺序 class TMetaclass(type): def __new__(cls,name,bases,attr ...

  3. Kotlin基本语法笔记3之定义类、继承及创建实例

    定义类 class MyObject private constructor(name: String, age: Int) { private var name: String private va ...

  4. python基础教程:定义类创建实例

    类的定义 在Python中,类通过class关键字定义,类名以大写字母开头 >>>class Person(object): #所有的类都是从object类继承 pass #pass ...

  5. [No000085]C#反射Demo,通过类名(String)创建类实例,通过方法名(String)调用方法

    using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Sy ...

  6. Javascript定义类(class)的三种方法

    将近20年前,Javascript诞生的时候,只是一种简单的网页脚本语言.如果你忘了填写用户名,它就跳出一个警告. 如今,它变得几乎无所不能,从前端到后端,有着各种匪夷所思的用途.程序员用它完成越来越 ...

  7. python之元编程(元类实例)

    本实例是元类实例,功能是记录该的子类的类名,并以树状结构展示子类的类名. RegisterClasses继承自type,提供的功能是在__init__接口,为类创建了childrens的集合,并类名保 ...

  8. C++中如何定义类和对象?

    在C++语言中,对象的类型被称为类,类代表了某一批对象的共性和特征. 类是对象的抽象,而对象是类的具体实例.如同C中的结构体一样,我们要先定义一个结构体,再使用结构体去定义一个变量.同一个结构体可以定 ...

  9. 疯狂java学习笔记之面向对象(一) - 定义类、方法、构造器

    Java面向对象 1.定义类 2.创建对象.调用方法 类和对象: 某一类对象的概念定义. 比如:人类 - 抽象出来的概念(不特指某个人) 对象 - 在类的概念下产生的一个实例,它就是一个对象了. ja ...

随机推荐

  1. JVM-ClassLoader类加载器

    类加载器: 对于虚拟机的角度来看,只存在两种类加载器: 启动类加载器(Brootstrap ClassLoader)和“其他类加载器”.启动类加载器是由C++写的,属于虚拟机的一部分,其他类加载器都是 ...

  2. PHP在 win7 64位 旗舰版 报错 Call to undefined function curl_init()

    代码在ubuntu下无缝运行OK 转到我的win7 64位 期间 学习机上 报错: Call to undefined function curl_init() 因为用到curl 远程抓取数据. 所以 ...

  3. JS实现瀑布流

    HTML:先让图片充满一页 <!DOCTYPE html> <html> <head lang="en"> <meta charset=& ...

  4. [心平气和读经典]The TCP/IP Guide(001)

    The TCP/IP Guide[Page 40,41] Introduction To the TCP/IP Guide | TCP/IP指南概述 As I sit here writing thi ...

  5. FocusBI:地产分析&雪花模型

    微信公众号:FocusBI关注可了解更多的商业智能.数据仓库.数据库开发.爬虫知识及沪深股市数据推送.问题或建议,请关注公众号发送消息留言;如果你觉得FocusBI对你有帮助,欢迎转发朋友圈或在文章末 ...

  6. jquery validate(转)

    转自:http://blog.sina.com.cn/s/blog_608475eb0100h3h1.html 官网地址:http://bassistance.de/jquery-plugins/jq ...

  7. Android6.0内核移植(1):分析编译日志

    在下面命令之后产生的编译日志进行分析 source build/envsetup.sh lunch sabresd_6dq-user make -j20 ======================= ...

  8. Node.js之Console用法小结

    /** * Created by city--online on 16/3/9. */ //console.time()和console.timeEnd()输出中间代码的执行时间(注意:time和ti ...

  9. SQL SERVER学习1——数据库概念

    <SQL Server实例教程>(科学出版社) 数据库的基本概念 数据是载荷信息的物理符号,是数据库中存储的基本对象. 信息可以通过手势,眼神表达,但是表达信息的最佳方式还是数据. 数据有 ...

  10. Java学习--Java 中的包装类

    Java 中的包装类 相信各位小伙伴们对基本数据类型都非常熟悉,例如 int.float.double.boolean.char 等.基本数据类型是不具备对象的特性的,比如基本类型不能调用方法.功能简 ...