"""
面向对象编程
Author:黄骏捷
Date:2019-09-29
"""
"""
定义类,使用类
"""
"""
class Student(object):
#__init__是一个特殊方法用于在创建对象时进行初始化操作
def __init__(self,name,age):
self.name = name
self.age = age
def study(self,course_name):
print('%s正在学习%s.' %(self.name,course_name))
#PEP 8要求标识符的名字用全小写多个单词用下划线连接
# 但是部分程序员和公司更倾向于使用驼峰命名法
def watch_movie(self):
if self.age<18:
print('%s只能看《熊出没》.' % self.name)
else:
print('%s正在观看岛国爱情大电影.' % self.name)
def main():
stu1 = Student('黄骏捷',19)
stu1.study('python真好玩')
stu1.watch_movie()
if __name__ == '__main__':
main()
"""
"""
如果希望属性是私有的,在给属性命名时可以用两个下划线作为开头
"""
"""
class Test:
def __init__(self, foo):
self.__foo = foo
def __bar(self):
print(self.__foo)
print('__bar')
def main():
test = Test('hello')
# AttributeError: 'Test' object has no attribute '__bar'
test.__bar()
# AttributeError: 'Test' object has no attribute '__foo'
print(test.__foo)
if __name__ == "__main__":
main()
"""
"""
Python并没有从语法上严格保证私有属性或方法的私密性,
它只是给私有的属性和方法换了一个名字来妨碍对它们的访问,
事实上如果你知道更换名字的规则仍然可以访问到它们
"""
class Test:
def __init__(self, foo):
self.__foo = foo
def __bar(self):
print(self.__foo)
print('__bar')
def main():
test = Test('hello')
test._Test__bar()
print(test._Test__foo)
if __name__ == "__main__":
main()
Day8_Object_Oriented1
猜你喜欢
转载自blog.csdn.net/ACofKing/article/details/101792589
今日推荐
周排行