您的位置:首页 > 编程语言 > Python开发

python基础—面向对象

2017-04-05 23:19 316 查看
感觉和java相比一个是大公司,一个是小公司, 大公司规范有文档,小公司简约效率高

面向对象
# 成员属性名称前 加上 __ 意为private
# get / set : get_name() set_name(name)
class Student:
def __init__(self, name, age):
self.name = name
self.age = age

def detail(self):
print(self.name)
print(self.age)

class PrimaryStudent(Student): # inherent
def lol(self):
print('can not win then run faster than others')

class CollegeStudent(Student):
def __init__(self, name, age, gf): # overrite构造函数
self.name = name
self.age = age
self.gf = gf

def gf_detail(self):
print(self.gf)

obj1 = PrimaryStudent('小学生', 7)
obj1.lol()
obj1.detail()

obj2 = CollegeStudent('王思聪', 29, '张雨欣')
obj2.detail()
obj2.gf_detail()

print(dir(obj1)) # class info as list
print(hasattr(obj1, 'name')) # True
setattr(obj1, 'name', 'jack')
print(getattr(obj1, 'name')) # jack
print(getattr(obj1, 'name', 404)) # jack
fn = getattr(obj1, 'detail') #7
fn()

# 实例属性和类属性
class Student(object):
name = 'Student'
def __init__(self, name):
self.name = name # 类属性
s = Student('Bob')
s.score = 90 # 实例属性

print(s.name)
s.name = 'Jack' # 给实例属性绑定name属性, 实例属性优先级比类属性高
print(s.name) # Jack
print(Student.name) # Student
del s.name # 删除实例name属性
print(s.name) # Student


I'm fish, I'm on.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python