python类的高级属性
---恢复内容开始---
类方法:通过@classmethod装饰器实现,类方法和普通方法的区别是,类方法只能访问类变量,不能访问实例变量,代码如下:
class Person(object):
def __init__(self,name):
self.name = name
@classmethod
def eat(self): print("%s is eating"%self.name)
d = Person("alex")
d.eat()
报错如下:
C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/类方法.py
Traceback (most recent call last):
File "D:/python开发代码/Python之路/作业/day8/类方法.py", line 9, in <module>
d.eat()
File "D:/python开发代码/Python之路/作业/day8/类方法.py", line 7, in eat
print("%s is eating"%self.name)
AttributeError: type object 'Dog' has no attribute 'name'
定义一个类变量后,代码如下:
class Person(object):
name = "parktrick"
def __init__(self,name):
self.name = name
@classmethod
def eat(self): print("%s is eating"%self.name)
d = Person("alex")
d.eat()
运行结果:
C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/类方法.py
parktrick is eating Process finished with exit code 0
静态方法:@staticmethod装饰器即可把其装饰的方法变为一个静态方法,静态方法的特点是不可以访问实例变量或类变量,但是可以调用时主动传递实例本身给eat方法,即d.eat(d),操作代码如下:
未使用类名调用方法的场景:
class Dog(object):
def __init__(self,name):
self.name = name
@staticmethod #把eat变成静态方法
def eat(self):
print("%s is eating"%self.name)
d = Dog("alex")
#调用时主动传递实例本身给eat方法,即d.eat(d)
d.eat()
运行结果:
C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/静态方法.py
Traceback (most recent call last):
File "D:/python开发代码/Python之路/作业/day8/静态方法.py", line 9, in <module>
d.eat()
TypeError: eat() missing 1 required positional argument: 'self' Process finished with exit code 1
报错显示eat方法需要个参数,但我们明明传了alex啊,所以说静态方法无法访问实例中的变量,那定义一个类变量呢?看下面:
class Dog(object):
name = "parktrick" #定义了一个类变量,看看运行结果
def __init__(self,name):
self.name = name
@staticmethod #把eat变成静态方法
def eat(self):
print("%s is eating"%self.name)
d = Dog("alex")
#调用时主动传递实例本身给eat方法,即d.eat(d)
d.eat()
运行结果:
C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/静态方法.py
Traceback (most recent call last):
File "D:/python开发代码/Python之路/作业/day8/静态方法.py", line 10, in <module>
d.eat()
TypeError: eat() missing 1 required positional argument: 'self' Process finished with exit code 1
结果显示报错,所以由此可以看出静态方法无法访问实例变量和类变量
看看正确姿势,通过调用时主动传递实例本身给eat方法,代码如下:
class Dog(object):
# name = "parktrick"
def __init__(self,name):
self.name = name
@staticmethod #把eat变成静态方法
def eat(self):
print("%s is eating"%self.name)
d = Dog("alex")
#调用时主动传递实例本身给eat方法,即d.eat(d)
d.eat(d)
运行结果:
C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/静态方法.py
alex is eating Process finished with exit code 0
属性方法:通过@property把一个方法变成一个静态属性,既然是属性,就可以直接使用实例化对象调用了,比如d.walk,代码如下:
class Person(object):
def __init__(self,name):
self.name = name
@property
def walk(self):
print("%s is walking"%self.name)
test = Person("Parktrick")
test.walk #直接使用实例化对象调用walk,不用加小括号
运行结果如下:
C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/属性方法.py
Parktrick is walking Process finished with exit code 0
如果加了括号就会报错了,结果如下所示:
C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/属性方法.py
Traceback (most recent call last):
File "D:/python开发代码/Python之路/作业/day8/属性方法.py", line 8, in <module>
test.walk()
TypeError: 'NoneType' object is not callable
Parktrick is walking
静态属性的作用:
比如一个航班当前的状态,是到达了还是延迟了,取消了还是已经飞走了,想知道这种状态需要经历以下几步:
1. 连接航空公司API查询
2. 对查询结果进行解析
3. 返回结果给你的用户
因此这个status属性的值是一系列动作后才得到的结果,所以你每次调用时,其实它都要经过一系列的动作才返回你结果,但这些动作过程不需要用户关心, 用户只需要调用这个属性就可以了。代码如下:
class Flight(object):
def __init__(self,name):
self.flight_name = name
def check_status(self):
print("check flight %s status" %self.flight_name)
return 1
@property
def flight_status(self):
status = self.check_status()
# print(status)
if status == "":
print("飞机已起飞")
elif status == "":
print("飞机未起飞")
elif status == "":
print("飞机就没有飞过")
@flight_status.setter #修改
def flight_status(self,status):
status_dic = {
0:"flying",
1:"not flying",
2:"none flying"
}
print("\033[31mHas changed the flight status to \033[0m",status_dic.get(status)) test = Flight("国航")
# test.check_status()
test.flight_status
test.flight_status = 2
运行结果如下:
C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/航班.py
check flight 国航 status
Has changed the flight status to none flying Process finished with exit code 0
再看一个廖大神举的例子:
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self,value):
if not isinstance(value,int):
raise ValueError("score must be an integer")
if value < 0 or value > 100:
raise ValueError("score must be 0-100")
self._score = value
test = Student()
test.score = 100
print(test.score)
总而言之,Python内置的@property
装饰器就是负责把一个方法变成属性调用的。
类的特殊成员方法
__doc__
class Person(object):
'''测试类的成员变量'''
def walk(self):
pass
P = Person()
print(P.__doc__)
运行结果:
C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/类的特殊成员便令.py
测试类的成员变量 Process finished with exit code 0
__dict__ 查看类或对象中的所有成员
class Province:
country = "china"
def __init__(self,name,count):
self.name = name
self.count = count
def func(self,*args,**kwargs):
print("func")
#获取类的成员,即:静态字段、方法
print(Province.__dict__) obj1 = Province("Hebei",10000)
print(obj1.__dict__)
#获取对象obj1的成员
__getitem__、__setitem__、__delitem__
class Foo(object):
def __getitem__(self, key):
print('__getitem__', key) def __setitem__(self, key, value):
print('__setitem__', key, value) def __delitem__(self, key):
print('__delitem__', key)
obj = Foo()
result = obj["k1"] #自动触发执行__getitem__
obj["k2"] = "alex" #自动触发执行__setitem
del obj["k1"]
运行结果:
C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/类的特殊成员便令.py
__getitem__ k1
__setitem__ k2 alex
__delitem__ k1 Process finished with exit code 0
反射:通过字符串映射或修改程序运行时的状态、属性、方法
利用反射查看面向对象成员归属
class Foo:
def __init__(self,name):
self.name = name
def show(self):
print("show")
obj = Foo("as")
#如果是类,就可以找到类中成员,运行结果为Bool值,找到了就显示True,没找到就显示False
print(hasattr(Foo,"show"))
#如果是对象,既可以找到对象,也可以找到类中的成员
print(hasattr(obj,"name"))
print(hasattr(obj,"show"))
运行结果:
C:\python3.5\python.exe D:/python开发代码/Python之路/作业/day8/类的特殊成员便令.py
True
True
True Process finished with exit code 0
未完待续。。。。
python类的高级属性的更多相关文章
- Python 类的高级属性(可选)
1.slots实例:限制类的实例有合法的属性集,只有__slots__属性列表中的属性才可能成为实例属性. 对象的实例通常没有一个属性字典,可以在__slots__列表中包含一个属性字典__dict_ ...
- Python 类的私有属性与私有方法
1.隐藏的使用场景 在Python类中,有些属性和方法只希望在对象的内部被使用,而不希望在外部被访问到, 2.定义方式, 在属性名或方法名前增加两个下划线,定义的就是私有属性或方法 #其实这仅仅这是一 ...
- Python——类的高级主题
介绍关于类的一些高级主题,这些是可选的,在Python应用程序中,不会常常遇到. =========================================================== ...
- python 类的私有属性和方法 (转载)
转载:http://www.runoob.com/python/python-object.html 类属性与方法 类的私有属性 __private_attrs:两个下划线开头,声明该属性为私有,不能 ...
- Python 简明教程 --- 20,Python 类中的属性与方法
微信公众号:码农充电站pro 个人主页:https://codeshellme.github.io 与客户保持良好的关系可以使生产率加倍. -- Larry Bernstain 目录 类中的变量称为属 ...
- Python类的私有属性
class Bar(object): __age = 18 sex = 'male' def __init__(self, ): pass def f(self): print(self.__age) ...
- Python类的特殊属性
Python中的特殊属性 定义如下类: class Foo(object): """Foo class definition""" 类的特殊 ...
- Python类的实例属性详解
实例属性 1.类被实例化后才会具有的属性 2.一般在_init_()方法中创建并初始化 3.直接使用即定义:self.<属性名> 4.引用方法:self.<属性名> 5.sel ...
- python类的__slots__属性、__del__属性、上下文(__enter__和__exit__)、
常规情况下,类的属性字典是共享的,而实例的字典是独立的.如果一个类的属性较少,但是拥有很多的实例,这些实例的属性字典会占用较多的内存空间.对这样的类来说,为了节省内存空间,可以使用__slots__类 ...
随机推荐
- “Ceph浅析”系列之一——前言
开源技术专家章宇同学(@一棹凌烟)在C3沙龙分享过Ceph之后,最近来了劲头,一口气写了一系列<Ceph浅析>的博文,共8篇: "Ceph浅析"系列之一--前言 &qu ...
- Jquery-下拉列表设置默认选择
$('#select option:eq(2)').attr('selected','selected');
- 用git管理源代码
自从做iOS开发的一年多以来,之前一直都是用svn进行代码管理.因为工作需要,我也开始用git管理源代码.关于git的基本使用,在此做一个详细的介绍,希望能对初次接触git的人有所帮助! 本篇博客针对 ...
- BeautifulSoup_python3
1.错误排除 bsObj = BeautifulSoup(html.read()) 报错: UserWarning: No parser was explicitly specified, so I' ...
- python 学习笔记12(序列常用方法总结)
http://www.cnblogs.com/vamei/archive/2012/07/19/2599940.html 多回想!!! 1. 序列(list,tuple,string) len(s) ...
- 【BZOJ-3709】Bohater 贪心
3709: [PA2014]Bohater Time Limit: 5 Sec Memory Limit: 128 MBSec Special JudgeSubmit: 835 Solved: ...
- ZooKeeper分布式集群安装
我特意选择了稳定版...... 奇数意思是说奇数和偶数对故障的容忍度是一致的....所以建议配置奇数个,并不是必须奇数... 一.master节点上安装配置 1.下载并解压ZooKeeper-3.4. ...
- springMVC-数据绑定流程
1.Spring MVC主框架将ServletRequest对象以及目标方法的入参实例传递给WebDataBinderFactory实例,以创建DataBinder(数据绑定器)实例对象 2.Data ...
- PHP Opcode内核实现 - [ PHP内核学习 ]
catalogue . Opcode简介 . PHP中的Opcode . opcode翻译执行(即时解释执行) 1. Opcode简介 opcode是计算机指令中的一部分,用于指定要执行的操作, 指令 ...
- dedecms /member/myfriend_group.php SQL Injection Vul
catalog . 漏洞描述 . 漏洞触发条件 . 漏洞影响范围 . 漏洞代码分析 . 防御方法 . 攻防思考 1. 漏洞描述 Dedecms会员中心注入漏洞 Relevant Link http:/ ...