公有,所有的地方都能访问到
私有,只有自己可以访问到,子类也访问不到
#共有和私有,加双下划线表示私有:只有在内部能访问,在外部访问不了。儿子也访问不了
class Foo:
__x = 1
@staticmethod
def func():
print(Foo.__x)
# print(Foo.__x)
Foo.func()
class Foo:
def __fun(self):
print("msg")
def show(self):
print("show")
self.__fun()
obj = Foo()
obj.show()
#基类也访问不到
class Base:
def __f1(self):
print("Base.f1")
class Foo(Base):
def fun(self):
self.__f1()
obj = Foo()
obj.fun()
#强制访问
class Foo:
def __init__(self,name):
self.__x = name
obj = Foo("yang")
print(obj._Foo__x)
#输出的结果为“yang”
class Foo(object):#在python2中称为:新市类
print("yang")
class Foo: #在python3中称为:经典类
print("zi")
#在python3中这两种的表示方法时一样的,因为所有的类不写,都会默认继承Object类。
Foo() #类 ()自动执行init方法
class School():
def __init__(self,title,addr):
self.title = title
self.address = addr
class ClassRoom():
def __init__(self,name,school_object):
self.name = name
self.school = school_object
s1 = School("北京","沙河")
s2 = School("上海","浦东")
s3 = School("深圳","南山")
c1 = ClassRoom("全栈21期",s1)
c1.name
c1.school.title
print(c1.school.address)
#其与列表类似,均可嵌套使用
飒飒大扫除## 成员修饰符与类的嵌套
公有,所有的地方都能访问到
私有,只有自己可以访问到,子类也访问不到
#共有和私有,加双下划线表示私有:只有在内部能访问,在外部访问不了。儿子也访问不了
class Foo:
__x = 1
@staticmethod
def func():
print(Foo.__x)
# print(Foo.__x)
Foo.func()
class Foo:
def __fun(self):
print("msg")
def show(self):
print("show")
self.__fun()
obj = Foo()
obj.show()
#基类也访问不到
class Base:
def __f1(self):
print("Base.f1")
class Foo(Base):
def fun(self):
self.__f1()
obj = Foo()
obj.fun()
#强制访问
class Foo:
def __init__(self,name):
self.__x = name
obj = Foo("yang")
print(obj._Foo__x)
#输出的结果为“yang”
class Foo(object):#在python2中称为:新市类
print("yang")
class Foo: #在python3中称为:经典类
print("zi")
#在python3中这两种的表示方法时一样的,因为所有的类不写,都会默认继承Object类。
Foo() #类 ()自动执行init方法
class School():
def __init__(self,title,addr):
self.title = title
self.address = addr
class ClassRoom():
def __init__(self,name,school_object):
self.name = name
self.school = school_object
s1 = School("北京","沙河")
s2 = School("上海","浦东")
s3 = School("深圳","南山")
c1 = ClassRoom("全栈21期",s1)
c1.name
c1.school.title
print(c1.school.address)
#其与列表类似,均可嵌套使用
原文:https://www.cnblogs.com/yangzilaing/p/13991603.html