#括号用于继承 继承人的类
class
TUser
():
#使用构造器可以不定义变量
# username=''
#password=''
def
__init__
(
self
,
username
,
password
):
#构造器
self
.username
=
username
self
.password
=
password
def
__str__
(
self
):
#定义输出对象名时直接返回的值
return
'{username:'
+
self
.username
+
','
+
'password:'
+
self
.password
+
'}'
def
getPassword
(
self
):
#self 类实例化之后的对象 this
return
self
.password
#user1 = TUser()
#user1.username=input('username:')
#user1.password=input('password:')
#使用构造器
user1
=
TUser(
input
(
'username:'
),
input
(
'password:'
))
#print(user1.username)
#print(user1.getPassword())
print
(user1)
#没有__str__返回内存地址 有__str__函数返回函数中的内容
if
user1.username
==
'admin'
and
user1.password
==
'123456'
:
print
(
'登录成功!'
)
else
:
print
(
'fail'
)
#封装
class
TUser
():
def
__init__
(
self
,
username
,
password
):
#构造器
self
.__username
=
username
#__私有变量
self
.__password
=
password
#__私有变量
def
__str__
(
self
):
#定义输出对象名时直接返回的值
return
'{username:'
+
self
.__username
+
','
+
'password:'
+
self
.__password
+
'}'
def
setUsername
(
self
,
username
):
#封装性
self
.__username
=
username
def
setPassword
(
self
,
password
):
#封装性
self
.__password
=
password
def
getPassword
(
self
):
#封装
return
self
.__password
def
getUsername
(
self
):
#封装
return
self
.__username
#使用构造器
user1
=
TUser(
input
(
'username:'
),
input
(
'password:'
))
#print(user1.username)
#print(user1.getPassword())
print
(user1)
#没有__str__返回内存地址 有__str__函数返回函数中的内容
if
user1.getUsername()
==
'admin'
and
user1.getPassword()
==
'123456'
:
print
(
'登录成功!'
)
else
:
print
(
'fail'
)
#继承
class
TPerson
():
def
__init__
(
self
,
height
,
weight
):
self
.height
=
height
self
.weight
=
weight
def
run
(
self
):
self
.__think()
print
(
'running'
)
def
__think
(
self
):
print
(
'thinking...'
)
class
TUser
(
TPerson
):
def
__init__
(
self
,
username
,
password
,
height
,
weight
):
#构造器
TPerson.
__init__
(
self
,height,weight)
#父类构造器
self
.__username
=
username
#__私有变量
self
.__password
=
password
#__私有变量
def
__str__
(
self
):
#定义输出对象名时直接返回的值
return
'{username:'
+
self
.__username
+
','
+
'password:'
+
self
.__password
+
'}'
def
setUsername
(
self
,
username
):
#封装性
self
.__username
=
username
def
setPassword
(
self
,
password
):
#封装性
self
.__password
=
password
def
getPassword
(
self
):
#封装
return
self
.__password
def
getUsername
(
self
):
#封装
return
self
.__username
def
run
(
self
):
#方法重写
print
(
'car running...'
)
class
TSell
(
TPerson
):
def
__init__
(
self
,
height
,
weight
):
#构造器
TPerson.
__init__
(
self
,height,weight)
#父类构造器
def
run
(
self
):
print
(
'OFO running...'
)
新建test.py
#encoding utf-8
from
models.objects
import
TUser
#使用构造器
user1
=
TUser(
'admin'
,
'123'
,
170
,
50
)
print
(user1.height)
user1.run()
#user1.__think()私有方法不能直接调用
#多态
#使用构造器
user1
=
TUser(
'admin'
,
'123'
,
170
,
50
)
seller
=
TSell(
180
,
70
)
#此函数的定义叫做多态
def
getMethod
(
person
):
person.run()
getMethod(user1)
getMethod(seller)