# coding:utf-8
import traceback
class A(object):
__static_field = 'A_private static field'
public_static_field = 'A_public_static_field'
start_urls = "A_class_start_urls"
_one_line = "A_one_line"
def __init__(self):
(filename, line_number, function_name, text) = traceback.extract_stack()[-2]
self.name = text[:text.find('=')].strip()
self.start_urls = "object_start_urls"
if not hasattr(self, "_one_line"): # 类属性中有,也算类实例有
self._one_line = '123'
def __str__(self):
return self.name
def A_comm_func(self):
return "A_comm_func"
@classmethod
def A_classmethod(cls):
return "A_classmethod"
@staticmethod
def A_staticmethod():
return "A_staticmethod"
def repeat(self):
return "A_repeat"
def ree(self):
return self.__re()
def __re(self):
return "A__re"
class B(A):
B_public_field = "B_public_field"
__B_pri_field = 'B_pri_field'
_B_one_line = 'B_one_line'
public_static_field = "B_public_static_field"
_one_line = "B_one_line"
def repeat(self):
return "B_repeat"
def B_comm_func(self):
return "B_comm_func"
@classmethod
def B_classmethod(cls):
return "B_classmethod"
@staticmethod
def B_staticmethod():
return 'B_staticmethod'
a = A()
b = B()
print "--------------A.dict-----------"
print A.__dict__
print "--------------B.dict-----------"
print B.__dict__
print "------------ a.__dict__ -----------"
print a.__dict__
print "--------- b.dict -----------"
print b.__dict__
# print b.A_classmethod()
print B.A_classmethod()
print A._one_line
print a._one_line
print b._one_line # 先从自己__dict__找,在去类找,再到类的父类找
print B._one_line # 先从自己找,再去父类找
b._one_line = 'luanqibazao'
print b._one_line
class A(object):
total = 1
def set(self, value):
self.total = self.total + value
a = A()
print a.__dict__ # {}
print a.total # 1
a.set(10)
print a.__dict__ # {'total': 11}
print a.total # 11
class A(object):
total = 1
@classmethod #注意 和上例相比,此处为 类方法
def set(cls, value):
cls.total = value
print A.total # 1
a = A()
print a.__dict__ # {}
print a.total # 1
a.set(10)
print a.__dict__ # {}
print a.total # 10
print A.total # 10
b = A()
b.set(11)
print b.total #11
print b.__dict__ # {}
print A.total # 11
print A.__dict__ #{'total':11}
class A(object):
total = 1
@staticmethod #注意此处为静态方法
def set(value):
total = value
return total
print A.total # 1
a = A()
print a.__dict__ # {}
print a.total # 1
e = a.set(10)
print a.__dict__ # {}
print a.total # 1
print e #10
print A.total # 1
b = A()
f = b.set(11)
print b.total #1
print b.__dict__ # {}
print f # 11
print A.total # 1
print A.__dict__ #{'total':1}
静态字段 属于类所有,类、对象都可以访问
普通字段 在__init__ 中的,只能被对象访问
私有变量 如果该变量属于类,那么只能在类内部调用,对象和类都可以在内部访问。
如果该私有变量属于对象,那么只能由对象在内部访问,类也不能访问。
类方法、静态方法 类和对象都可以调用
普通方法 只能被对象调用,如果被类调用,需要传入一个对象参数