# -*- coding: encoding -*-
#静态方法
class Dog(object):
def __init__(self,name):
self.name = name
@staticmethod #把eat方法变为静态方法,1 调用时主动传实例本身到eat 2 去掉eat()方法中的self参数
def eat(): #例子中取的是第二种方法
print("chenronghua is eating")
d = Dog("chenronghua")
#d.eat(d)也是可行的,但是eat方法中要传self参数
d.eat()
# -*- coding: encoding -*-
#类方法
#类方法只能访问类变量,不能访问实例变量
class Dog(object):
name = "我是类变量!"
def __init__(self,name):
self.name = name
@classmethod #注意缩进,要和上边的构造函数保持一致
def eat(self):
print("%s is eating" % self.name)
d = Dog("chenronghua")
d.eat()
# -*- coding: encoding -*-
class Dog(object):
name = 'alex'
def __init__(self,name):
self.name = name
@property #加上此方法,可以把下边的方法看成Dog类的一个属性,一次装饰有效
def eat(self):
print("%s is eating" %self.name)
@classmethod #类方法
def drink(self):
print("%s is drinking" %self.name)
@staticmethod
def full(self):
print("%s is full up" %self.name)
d = Dog("chenronghua")
#调用属性方法下的eat属性
d.eat
#调用类方法下的drink方法
d.drink()
#调用静态方法下的eat方法
# -*- coding: encoding -*-
#对属性方法进行练习
class Flight(object):
def __init__(self,name):
self.flight_name = name
def checking_status(self):
print("checking flight %s status..." %self.flight_name)
#return 1
@property #静态属性
def flight_status(self,status):
#status = self.checking_status() #把上边的属性传递到下边?
if status == 0:
print("flight got canceled...")
elif status == 1:
print("flight is arrived...")
elif status == 2:
print("flight has departured already...")
else:
print("cannot confirm the fight status...please check later")
@flight_status.setter #修改
def flight_status(self,status):
status_dic = {
0:"canceled",
1:"arrived",
2:"departured"
}
print("\033[31;1mHas changed the flight status to \033[0m",status_dic.get(status) )
@flight_status.deleter #删除
def flight_status(self):
f.checking_status()
f.flight_status = 1 #触发flight_status.setter
del f.flight_status #触发flight_status.deleter
class film(object):
"""谍影重重5已经上映了,非常不错"""
def __init__(self,name):
self.name = name
def func(self):
"""这个功能还没定义,只是占个位子"""
print("it's about %s" %self.name)
print(film.__doc__)
t = film('spy')
def __init__(self):
pass
def __call__(self, name,*args, **kwargs):
self.name = name
obj('www.we.com') # 执行 __call__
class Province:
country = 'China'
def __init__(self, name, count):
self.name = name
self.count = count
def func(self, *args, **kwargs):
print(Province.__dict__)
print(obj1.__dict__)
# 获取 对象obj1 的成员
print(obj2.__dict__)
# 获取 对象obj1 的成员
# 输出:{'count': 3888, 'name': 'HeNan'}
class Foo:
def __str__(self):
return '这是要返回的值!'
obj = Foo()
print(obj)
# 输出:这是要返回的值
#Author is wspikh
# -*- coding: encoding -*-
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']
obj['k2'] = 'alex'
import importlib
__import__ ( 'import_lib.metaclass' ) #这是解释器自己内部用的
#importlib.import_module('import_lib.metaclass') #与上面这句效果一样,官方建议用这个 |
#!/usr/bin/env python
#Author is wspikh
# -*- coding: encoding -*-
#hasattr 和 getattr都是内建函数
class A:
def __init__(self):
self.name = 'zhangjing'
#self.age = 24 def method(self):
print("method print") Instance = A()
print(getattr(Instance,'name','not find')) #如果Instance对象中有属性
#name则打印self.name的值,否则就打印'not find
print(getattr(Instance,'age','not find')) #如果Instance对象中有属性age则打印self.age的值,否则打印'not find'
print(getattr(A,'method','default')) #如果有方法method,就打印其地址,否则打印default
#print(getattr(A,'method','default'))() #如果有方法method,运行函数并打印None否则打印default #hasattr getattr setattr练习
class Employee:
'所有员工的基类'
empCount = 0 def __init__(self, name, salary):
self.name = name
self.salary = salary
#加1
Employee.empCount += 1 def displayCount(self):
print("Total Employee %d" % Employee.empCount) def displayEmployee(self):
print("Name : ", self.name, "\nSalary: ", self.salary) Xiaoxiao = Employee('Xiaoxiao', 2000)
setattr(Xiaoxiao, 'age', 21) Tiny = Employee("Tiny", 5000)
setattr(Tiny, 'age', 23) print("实例类的第一个对象 Xiaoxiao ");
print('Xiaoxiao 是否存在age属性:', hasattr(Xiaoxiao, 'age'))
Xiaoxiao.displayEmployee();
print("Age:", getattr(Xiaoxiao, 'age', 'not find'));
#对象中是否有SEX属性,有就返回值,没有就返回not find
print("Sex:", getattr(Xiaoxiao, 'sex', 'not find'));
print("\n") print("实例类的第二个对象 Tiny")
print('Tiny 是否存在age属性:', hasattr(Tiny, 'age'))
Tiny.displayEmployee()
print("Age: ", getattr(Tiny, 'age', 'not find')); print("\n")
print("Total Employee number: %d" % Employee.empCount)
print("\n")
- 如果在try后的语句里发生了异常,却没有匹配的except子句,异常将被递交到上层的try,或者到程序的最上层(这样将结束程序,并打印缺省的出错信息)。
- 如果在try子句执行时没有发生异常,python将执行else语句后的语句(如果有else的话),然后控制流通过整个try语句
# -*- coding: encoding -*-
"""import sys,traceback
try:
a = 1
b = a
c = w
except Exception as e:
print(Exception,":",e)
try:
a = b
b = c
except:
f = open('log.txt','a')
traceback.print_exc(file=f)
f.flush()
f.close()
"""
try:
fh = open('testfile','w')
print("Error: 没有找到文件或读取文件失败")
else:
print("内容写入文件成功")