主題: 假設想要多個可信認的user共用一台機器,每個user有權限可以轉換身分到root
How to ?
1. 加入一般身分的user2. 修改visudo
#!/usr/bin/python
from pympler import asizeof
class A(object):
#__slots__ = ['year', 'month', 'day']
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
a = A(1,2,3)
print asizeof.asized(a, detail=1).format()
<__main__ data-blogger-escaped-.a="" data-blogger-escaped-0x7f15e50e9cd0="" data-blogger-escaped-at="" data-blogger-escaped-object=""> size=552 flat=64
__dict__ size=488 flat=280
__class__ size=0 flat=0
使用__slots__優化記憶體(不存table, 分開以更節省記憶體的方式存)
#!/usr/bin/python
from pympler import asizeof
class A(object):
__slots__ = ['year', 'month', 'day']
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
a = A(1,2,3)
print asizeof.asized(a, detail=1).format()
<__main__ data-blogger-escaped-.a="" data-blogger-escaped-0x191f6c8="" data-blogger-escaped-at="" data-blogger-escaped-object=""> size=224 flat=72
__slots__ size=80 flat=80
month size=24 flat=24
day size=24 flat=24
year size=24 flat=24
__class__ size=0 flat=0
class A(object):
def __init__(self):
print ("A init")
@property
def name(self):
print ("A name getter")
@name.setter
def name(self, x):
print ("A name setter")
我們想要對A的name property繼承,並且改寫。
改寫的方式想要繼承A原本的一些code再附加新的class的一些code,可以這樣寫:
class B(A):
def __init__(self):
print ("B init")
@property
def name(self):
super(B, B).name.fget(self)
print ("B name getter")
@name.setter
def name(self, x):
super(B, B).name.fset(self, x)
print ("B name setter")
class B(A):
def __init__(self):
print ("B init")
@property
def name(self):
super(B, B).name.__get__(self)
print ("B name getter")
@name.setter
def name(self, x):
super(B, B).name.__set__(self, x)
print ("B name setter")
#!/usr/bin/python
class A(object):
def __init__(self):
print ("A init")
@property
def name(self):
print ("A name getter")
@name.setter
def name(self, x):
print ("A name setter")
class B(A):
def __init__(self):
print ("B init")
@property
def name(self):
super(B, B).name.__get__(self)
print ("B name getter")
b = B()
b.name
b.name = 3
B init A name getter B name getter Traceback (most recent call last): File "./property.py", line 25, inb.name = 3 AttributeError: can't set attribute Shell 已返回1
#!/usr/bin/python
class A(object):
def __init__(self):
pass
def test1(self):
print "test1"
def __test2(self):
print "test2"
class B(A):
def __init__(self):
pass
b = B()
b.test1()
b.__test2()
結果:(注意test1有印出來但呼叫__test2時發生AttributeError的Exception)
test1 Traceback (most recent call last): File "./private.py", line 18, inb.__test2() AttributeError: 'B' object has no attribute '__test2'
#!/usr/bin/python
class A(object):
def __init__(self):
print ("[A]")
class A0(A):
def __init__(self):
super(A0, self).__init__()
print ("[A0]")
class A1(A):
def __init__(self):
super(A1, self).__init__()
print ("[A1]")
class A2(A):
def __init__(self):
super(A2, self).__init__()
print ("[A2]")
class A21(A2):
def __init__(self):
super(A21, self).__init__()
print ("[A21]")
class A22(A2):
def __init__(self):
super(A22, self).__init__()
print ("[A22]")
class B(A1, A21, A22, A0):
def __init__(self):
super(B, self).__init__()
B()
結果: (所有class的__init__都被剛好執行一次, 且有parent/child繼承關係parent一定會比child先做)[A] [A0] [A2] [A22] [A21] [A1]
#!/usr/bin/python
class A:
def __init__(self):
print "__init__"
def __enter__(self):
print "__enter__"
return self
def __exit__(self, exc_ty, exc_val, tb):
print "__exit__"
a = A()
with a:
print " in with "
__init__ __enter__ in with x=<__main__ data-blogger-escaped-.a="" data-blogger-escaped-0x7faa8553ac68="" data-blogger-escaped-at="" data-blogger-escaped-instance=""> __exit__
#!/usr/bin/python
class A:
def __init__(self):
print "__init__"
def __enter__(self):
print "__enter__"
def __exit__(self, exc_ty, exc_val, tb):
print "__exit__"
a = A()
with a as x:
print " in with x=%r" % x
__init__ __enter__ in with x=None __exit__
#!/usr/bin/python
#!/usr/bin/python
class B:
def __init__(self):
pass
def showB(self):
print "This is B"
class A:
def __init__(self):
print "__init__"
def __enter__(self):
print "__enter__"
return B()
def __exit__(self, exc_ty, exc_val, tb):
print "__exit__"
a = A()
with a as b:
print " in with "
b.showB()
__init__ __enter__ in with This is B __exit__
#!/usr/bin/python
class A:
def __init__(self):
print "__init__"
def __enter__(self):
print "__enter__"
return self
def __exit__(self, exc_ty, exc_val, tb):
print "__exit__ %r %r %r" % (exc_ty, exc_val, tb)
a = A()
with a as x:
print " in with x=%r" % x
raise Exception("exp1234")
__init__ __enter__ in with x=<__main__ data-blogger-escaped-.a="" data-blogger-escaped-0x7f1c4bc0ac68="" data-blogger-escaped-at="" data-blogger-escaped-instance=""> __exit__Exception('exp1234',) Traceback (most recent call last): File "./with.py", line 16, in raise Exception("exp1234") Exception: exp1234
#!/usr/bin/python
class A:
def __init__(self, x, y):
self.x = x
self.y = y
a = A(5, 6)
print a
print "%r" % a
print "{0!r}".format(a)
print str(a)
<__main__ data-blogger-escaped-.a="" data-blogger-escaped-0x7f433e42db48="" data-blogger-escaped-at="" data-blogger-escaped-instance=""> <__main__ data-blogger-escaped-.a="" data-blogger-escaped-0x7f433e42db48="" data-blogger-escaped-at="" data-blogger-escaped-instance=""> <__main__ data-blogger-escaped-.a="" data-blogger-escaped-0x7f433e42db48="" data-blogger-escaped-at="" data-blogger-escaped-instance=""> <__main__ data-blogger-escaped-.a="" data-blogger-escaped-0x7f433e42db48="" data-blogger-escaped-at="" data-blogger-escaped-instance="">
#!/usr/bin/python
class A:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return 'This is A __str__'
def __repr__(self):
return '<A __repr__>'
a = A(5, 6)
print a
print "%r" % a
print "{0!r}".format(a)
print "{0!s}".format(a)
print str(a)
This is A __str__ <A __repr__> <A __repr__> This is A __str__ This is A __str__
#!/usr/bin/python
import inspect
def myfunc(a, b=2, c=1, *args, **kwargs):
print ("%r %r %r" % (a,b,c))
return a
argspec = inspect.getargspec(myfunc)
print (str(argspec))
ArgSpec(args=['a', 'b', 'c'], varargs='args', keywords='kwargs', defaults=(2, 1))
#!/usr/bin/python3
from functools import partial
def myfunc(x, y, z):
print ("%r %r %r" % (x,y,z))
binded_myfunc = partial(myfunc, 2, 3, 4)
myfunc(1,2,3)
binded_myfunc()
結果:
1 2 3 2 3 4
#!/usr/bin/python3
print ("This is python code")
<pre class='codeblock'>#!/usr/bin/python
import time
from functools import wraps
def timethis(func):
'''
Decorator that reports the excution time
'''
#@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, end-start)
return result
return wrapper
@timethis
def countdown(n):
'''
Counts down
'''
while n > 0:
n -= 1
countdown(10000)
print countdown.__name__
print countdown.__doc__
<\pre>
#!/usr/bin/python3
from functools import wraps, partial
import logging
def logged(level, name=None, message=None):
print ("%r %s" % (locals(), "0"))
def decorate(func):
logname = name if name else func.__module__
log = logging.getLogger(logname)
logmsg = message if message else func.__name__
print ("%r %s" % (locals(), "1"))
@wraps(func)
def wrapper(*args, **kwargs):
print ("%r %s" % (locals(), "2"))
log.log(level, logmsg)
return func(*args, **kwargs)
return wrapper
return decorate
@logged(logging.DEBUG)
def add(x, y):
return x + y
注意,一樣add並沒有被呼叫, 但結果如下: