Python3 系列之 面向对象篇
面向对象的三大特性:继承、封装和多态
Python 做到胶水语言,当然也支持面向对象的编程模式。
封装
class UserInfo(object):
lv = 5
def __init__(self, name, age, account):
self.name = name
self._age = age
self.__account = account
def get_account(self):
return self.__account
@classmethod
def get_name(cls):
return cls.lv
@property
def get_age(self):
return self._age
if __name__ == "__main__":
userinfo = UserInfo("hippie", 26, 123456)
print(dir(userinfo))
print(userinfo.__dict__)
print(userinfo._age)
print(userinfo.get_account())
print(userinfo._UserInfo__account)
print(UserInfo.lv)
print(userinfo.get_age)
继承
class UserInfo(object):
lv = 5
def __init__(self, name, age, account):
self.name = name
self._age = age
self.__account = account
@property
def get_account(self):
return self.__account
class UserInfo2(UserInfo):
@property
def get_account(self):
return super().get_account + 10
if __name__ == "__main__":
a = UserInfo("hippie", 26, 123456)
print(a.get_account)
b = UserInfo2("hippie", 26, 123456)
print(b.get_account)
print(isinstance(a, UserInfo))
print(isinstance(a, UserInfo2))
多态
class User(object):
def __init__(self, name):
self.name = name
def printUser(self):
print(self.name)
class UserVip(User):
def printUser(self):
print("Hello VIP:" + self.name)
class UserGeneral(User):
def printUser(self):
print("Hello User:" + self.name)
if __name__ == "__main__":
vip = UserVip("hippie")
vip.printUser()
vip = UserGeneral("jock")
vip.printUser()
总结
封装、继承和多态是面向对象中的重要思想,对于 Python 这种高级语言,虽然很多地方从语法上可以不用面向对象的思想,但是对于项目构建来说,面向对象是基本要求,这样做显然是很有必要的。