定义类/实例(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=''
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)的更多相关文章
- python之定义类创建实例
https://www.cnblogs.com/evablogs/p/6688938.html 类的定义 在Python中,类通过class关键字定义,类名以大写字母开头 1 2 >>&g ...
- python 类的定义 实例化 实例完后初始化
先来看看 类的__init__, 类的__new__ , 元类的__new__的执行顺序 class TMetaclass(type): def __new__(cls,name,bases,attr ...
- Kotlin基本语法笔记3之定义类、继承及创建实例
定义类 class MyObject private constructor(name: String, age: Int) { private var name: String private va ...
- python基础教程:定义类创建实例
类的定义 在Python中,类通过class关键字定义,类名以大写字母开头 >>>class Person(object): #所有的类都是从object类继承 pass #pass ...
- [No000085]C#反射Demo,通过类名(String)创建类实例,通过方法名(String)调用方法
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Sy ...
- Javascript定义类(class)的三种方法
将近20年前,Javascript诞生的时候,只是一种简单的网页脚本语言.如果你忘了填写用户名,它就跳出一个警告. 如今,它变得几乎无所不能,从前端到后端,有着各种匪夷所思的用途.程序员用它完成越来越 ...
- python之元编程(元类实例)
本实例是元类实例,功能是记录该的子类的类名,并以树状结构展示子类的类名. RegisterClasses继承自type,提供的功能是在__init__接口,为类创建了childrens的集合,并类名保 ...
- C++中如何定义类和对象?
在C++语言中,对象的类型被称为类,类代表了某一批对象的共性和特征. 类是对象的抽象,而对象是类的具体实例.如同C中的结构体一样,我们要先定义一个结构体,再使用结构体去定义一个变量.同一个结构体可以定 ...
- 疯狂java学习笔记之面向对象(一) - 定义类、方法、构造器
Java面向对象 1.定义类 2.创建对象.调用方法 类和对象: 某一类对象的概念定义. 比如:人类 - 抽象出来的概念(不特指某个人) 对象 - 在类的概念下产生的一个实例,它就是一个对象了. ja ...
随机推荐
- feignClient中修改ribbon的配置
1.使用@FeignClient注解发现服务 服务提供者的controller: @RestController public class StudentController { @Autowired ...
- SpringBoot集成WebSocket【基于STOMP协议】进行点对点[一对一]和广播[一对多]实时推送
原文详细地址,有点对点,还有广播的推送:https://blog.csdn.net/ouyzc/article/details/79884688 下面是自己处理的一些小bug 参考原文demo,结合工 ...
- SymbolTable
在ClassReader中有两个重要的属性,如下定义: /** A hashtable containing the encountered top-level and member classes, ...
- python-fork聊天室
服务端 #!/usr/bin/python from socket import * import sys import os class Node(object): def __init__(sel ...
- FocusBI:地产分析&雪花模型
微信公众号:FocusBI关注可了解更多的商业智能.数据仓库.数据库开发.爬虫知识及沪深股市数据推送.问题或建议,请关注公众号发送消息留言;如果你觉得FocusBI对你有帮助,欢迎转发朋友圈或在文章末 ...
- PHP的一些语句 if...else...elseif - Switch - while - for
条件语句用于基于不同条件执行不同的动作 PHP 条件语句 在您编写代码时,经常会希望为不同的决定执行不同的动作.您可以在代码中使用条件语句来实现这一 点. 在 PHP 中,我们可以使用以下条件语句: ...
- jQuery的三种$()方式
http://www.jb51.net/article/21660.htm $号是jQuery“类”的一个别称,$()构造了一个jQuery对象.所以,“$()”可以叫做jQuery的构造函数(个 ...
- 三、curator recipes之共享的可重入读写锁
简介 curator实现了跨JVM的可重入读写互斥锁.它使用zookeeper去进行加锁,所以指定相同路径的处理线程将会基于“公平锁”的机制去竞争锁资源. 读写锁包含了读锁.写锁两个,它们的互斥关系如 ...
- php分页实例及其原理
Part1:实例 /** * 取得上次的过滤条件 * @param string $param_str 参数字符串,由list函数的参数组成 * @return 如果有,返回array('filter ...
- C#可遍历的集合
public class Product { /// <summary> /// 自增ID /// </summary> public int ID { get; set; } ...