码迷,mamicode.com
首页 > 编程语言 > 详细

python基础4—面向对象

时间:2018-01-22 17:28:50      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:构造函数   成员   color   面向   nbsp   not   sel   王思聪   一个   

感觉和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

 

python基础4—面向对象

标签:构造函数   成员   color   面向   nbsp   not   sel   王思聪   一个   

原文地址:https://www.cnblogs.com/zeroones/p/8329497.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!