四、进阶语法
- 介绍“对象了”,注意看哈,代码可直接执行
#!/usr/bin/env
# coding:utf-8
__author__="bobolnear@163.com"
# self代表类的实例,而非类
# 类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称, 按照惯例它的名称是 self。
class Employee:
'所有员工的基类'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
def __del__(self):
class_name = self.__class__.__name__
print class_name, "销毁"
if __name__ == "__main__":
"创建 Employee 类的第一个对象"
emp1 = Employee("Zara", 2000)
"创建 Employee 类的第二个对象"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
print "-----------邪恶的分界线----------------"
#添加,删除,修改类的属性
hasattr(emp1, 'age') # 如果存在 'age' 属性返回 True。
setattr(emp1, 'age', 8) # 添加属性 'age' 值为 8
print "添加age=8后取值" , getattr(emp1, 'age') # 返回 'age' 属性的值
delattr(emp1, 'age') # 删除属性 'age'
#也可以简写 推荐写法
emp1.age = 7 # 添加一个 'age' 属性
print "添加age=7后取值" , emp1.age
emp1.age = 9 # 修改 'age' 属性
print "添加age=9后取值" ,emp1.age
del emp1.age # 删除 'age' 属性
print "-----------邪恶的分界线----------------"
#对象内置属性
print "Employee.__doc__:", Employee.__doc__
print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__
- 接下来介绍父子对象啦
#!/usr/bin/env
# coding:utf-8
__author__="bobolnear@163.com"
class Parent: # 定义父类
parentAttr = 100
def __init__(self):
print "调用父类构造函数"
def parentMethod(self):
print '调用父类方法'
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print "父类属性 :", Parent.parentAttr
class Child(Parent): # 定义子类 继承Parent 可以继承多个用,隔开
#__private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时
#self.__private_attrs。
__private_attrs = "我是私有的__private_attrs"
def __init__(self):
print "调用子类构造方法"
def childMethod(self):
print '调用子类方法 child method'
def privateAttrsMethod(self):
print "调用私有属性", self.__private_attrs
# __private_method:两个下划线开头,声明该方法为私有方法,不能在类地外部调用。在类的内部调用
# self.__private_methods
def __privateMethod(self):
print "调用私有函数"
if __name__ == "__main__":
c = Child() # 实例化子类
c.childMethod() # 调用子类的方法
c.parentMethod() # 调用父类方法
c.setAttr(200) # 再次调用父类的方法
c.getAttr() # 再次调用父类的方法
c.privateAttrsMethod()
五、初学者常见问题&小技巧
- python空格缩进格式很重要,如下图两个print空格不同报错:IndentationError: unindent does not match any outer indentation level,规范的写法用tab缩进也可以用2个或4个空格,不过我比较喜欢tab。
pycharm IDE的配色方案(Dracula-德古拉伯爵)想向我这样的同学可以看下图
在文件开头加入这句,是告诉操作系统执行这个脚本的时候,调用/usr/bin下的python解释器;
这在做项目时要注意,绝对一坑。env会自动去寻找。
#!/usr/bin/env
四、联系&感谢
本文部分代码 参考 runoob并进行测试修正