1 Star 0 Fork 3

tonyklose1984 / LearningPython

forked from celaraze / learning-python 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
19.类和实例.py 824 Bytes
一键复制 编辑 原始数据 按行查看 历史
绯末 提交于 2019-12-30 11:20 . 增加类和实例;增加访问控制
# 所有类最终都会继承object类,所以这里不知道选择什么好的话,直接就用object
class Student(object):
pass
# 实例化类
tom = Student()
print(tom)
# 实例后可以随意绑定属性
tom.name = 'tom'
tom.age = 18
print(tom.name)
print(tom.age)
# 可以在定义类的时候,把实例化必须绑定的属性也一起定义
# __init__相当于别的语言中的constract
class Teacher(object):
def __init__(self, name, age):
self.name = name
self.age = age
lily = Teacher('Lily', 18)
print(lily.name)
print(lily.age)
# 数据封装
class StudentTwo():
def __init__(self, name, age):
self.name = name
self.age = age
def print_age(self):
print('%s:%s' % (self.name, self.age))
# 打印值
tom = StudentTwo('Tom', 18)
tom.print_age()
Python
1
https://gitee.com/tonyklose1984/LearningPython.git
git@gitee.com:tonyklose1984/LearningPython.git
tonyklose1984
LearningPython
LearningPython
master

搜索帮助