# -*- coding: UTF-8 -*- //显示中文,中文编码
class Employee:
emCount = 0
'''类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称,
按照惯例它的名称是 self。self 代表类的实例,self 在定义类的方法时是必须有的,
虽然在调用时不必传入相应的参数。
'''
def __init__(self,name,age):
self.name = name
self.age = age
Employee.emCount += 1
def displayCount(self):
print "Total employee %d" %Employee.emCount
def displayEmployee(self):
print "name:",self.name,"age:",self.age
#创建新对象的方法
e=Employee("ss",23)
e.displayCount()
e.displayEmployee()
'''
在python中继承中的一些特点:
1:在继承中基类的构造(__init__()方法)不会被自动调用,它需要在其派生类的构造中亲自专门调用。
2:在调用基类的方法时,需要加上基类的类名前缀,且需要带上self参数变量。区别于在类中调用普通函数时并不需要带上self参数
3:Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。(先在本类中查找调用的方法,找不到才去基类中找)。
class C(A, B): # C继承类 A 和 B(多重继承)
'''
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): # 定义子类
def __init__(self):
print "调用子类构造方法"
def childMethod(self):
print '调用子类方法 child method'
c = Child() # 实例化子类
c.childMethod() # 调用子类的方法
c.parentMethod() # 调用父类方法
c.setAttr(200) # 再次调用父类的方法
c.getAttr() # 再次调用父类的方法
#运算符重载
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
class JustCounter:
__secretCount = 0 # 私有变量
publicCount = 0 # 公开变量
def count(self):
self.__secretCount += 1
self.publicCount += 1
print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.publicCount
#print counter.__secretCount # 报错,实例不能访问私有变量
print counter._JustCounter__secretCount
'''
单下划线、双下划线、头尾双下划线说明:
__foo__: 定义的是特列方法,类似 __init__() 之类的。
_foo: 以单下划线开头的表示的是 protected 类型的变量,即保护类型只能允许其本身与子类进行访问,不能用于 from module import *
__foo: 双下划线的表示的是私有类型(private)的变量, 只能是允许这个类本身进行访问了。
'''
Python面向对象
最新推荐文章于 2021-08-07 22:07:09 发布