单例模式
class Singleton(object):
def __new__(cls, *args, **kwargs):
if not '_instance' in cls.__dict__:
cls._instance = object.__new__(cls)
cls._instance = super(Singleton,cls).__new__(cls)
return cls._instance
函数调用, @classmethod, @property
python 可以使用类名加函数名的方式进行函数调用
print Program.get_age(program)
@classmethod 类似于java中的静态方法,不需要实例对象,直接类名调用
ClassName.get_class_name()
@property 将函数变成属性一样来调用
def get_method_name():
pass
instanceClass.get_method_name()
@property
def get_method_name():
pass
instanceClass.get_method_name
判断子类和实例
print isinstance(backProgram, Program)
print issubclass(NewType, Program)
python的初始化机制
class BackProgram(Program):
def __init__(self, name, age, description, sex):
super(BackProgram, self).__init__(name, age, description)
self.__sex = sex
print '__init__'
def __new__(cls, *args, **kwargs):
print args
print '__new__'
return super(BackProgram, cls).__new__(cls)
魔术方法
__add__, __eq__, __mul__, __div__, __sub__, __and__, __or__ 等运算符的魔术方法
def __add__(self, other):
if isinstance(other, MagicMethod):
return other.__age + self.__age
else :
raise TypeError(
"This is not MagicMethod's instance")
print oneMagicMethod + twoMagicMethods
__str__, __repr__, __dir__, 字符串显示,显示属性魔术方法
class Property(object):
def __init__(self, name):
self.__name = name
def __str__(self):
return 'Property name ' + self.__name
def __dir__(self):
return self.__dict__.keys()
def __repr__(self):
return 'jfskfjsl'
if __name__ ==
'__main__':
property = Property(
'name')
print property
print property.__dict__
getattribute, getattr, setattr, 这里getattribute和getattr的区别就是:getattr会在没有查找到相应实例属性时被调用, 而getattribute则每次都会调用
>>> class test():
... name=
"xiaohua"
... def run(self):
... return "HelloWord"
...
>>> t=test()
>>> getattr(t,
"name")
'xiaohua'
>>> getattr(t,
"run")
<bound method test.run of <__main__.test instance at
0x0269C878>>
>>> getattr(t,
"run")()
'HelloWord'
>>> getattr(t,
"age")
Traceback (most recent call last):
File
"<stdin>", line
1,
in <module>
AttributeError: test instance has no attribute
'age'
>>> getattr(t,
"age",
"18")
'18'
>>>
>>> class test():
... name=
"xiaohua"
... def run(self):
... return "HelloWord"
...
>>> t=test()
>>> hasattr(t,
"age")
False
>>> setattr(t,
"age",
"18")
>>> hasattr(t,
"age")
True
>>>
__main__函数
在python中,当一个module作为整体被执行时,moduel.__name__的值将是’__main__’;而当一个 module被其它module引用时,module.__name__将是module自己的名字,当然一个module被其它module引用时,其本身并不需要一个可执行的入口main了。
>>> import hello
>>> hello.__name__
'hello'
转载请注明原文地址: https://ju.6miu.com/read-200314.html