1、类方法
面向对象最重要的概念就是类(Class)和实例(Instance),必须牢记类是抽象的模板,比如Student类,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可能不同。对象是类的实例。换句话说,类主要定义对象的结构,然后我们以类为模板创建对象。类不但包含方法定义,而且还包含所有实例共享的数据。
1.1 封装
使用关键字 class 定义 Python 类,关键字后面紧跟类的名称、分号和类的实现。
class Turtle: # Python中的类名约定以大写字母开头
"""关于类的一个简单例子"""
# 属性
color = 'green'
weight = 10
legs = 4
shell = True
mouth = '大嘴'
# 方法
def climb(self):
print('努力的向前爬...')
def run(self):
print('飞快的向前跑...')
def bite(self):
print('学如逆水行舟...')
def eat(self):
print('活到老学到老...')
def sleep(self):
print('学习吃饭睡觉zzz')
tt = Turtle()
print(tt)
# <__main__.Turtle object at 0x0000007C32D67F98>
print(type(tt))
# <class '__main__.Turtle'>
print(tt.__class__)
# <class '__main__.Turtle'>
print(tt.__class__.__name__)
# Turtle
tt.climb() # 努力的向前爬....
tt.run() # 飞快的向前跑...
tt.bite() # 学如逆水行舟...
# Python类也是对象。它们是type的实例
print(type(Turtle)) # <class 'type'>
1、继承:子类自动共享父类之间数据和方法的机制
class MyList(list):
pass
lst = MyList([2020, 7, 28, 5, 20])
lst.append(9)
lst.sort()
print(lst) #[5, 7, 9, 20, 28, 2020]
2、多态:不同对象对同一方法响应不同的行动
class Animal:
def run(self):
raise AttributeError('子类必须实现这个方法')
class People(Animal):
def run(self):
print('不忘初心方得始终')
class Pig(Animal):
def run(self):
print('pig is walking')
class Dog(Animal):
def run(self):
print('dog is running')
def func(animal):
animal.run()
func(Pig()) # pig is walking
func(People()) # 不忘初心方得始终
3、Python 的 self 相当于 C++ 的 this 指针
class Test:
def prt(self):
print(self)
print(self.__class__)
t = Test()
t.prt()
# <__main__.Test object at 0x000000BC5A351208>
# <class '__main__.Test'>
2、对象方法
实例化类其他编程语言中一般用关键字 new,但是在 Python 中并没有这个关键字,类的实例化类似函数调用方式。以下使用类的名称 Employee 来实例化,并通过 init 方法接收参数。
"创建 Employee 类的第一个对象"
emp1 = Employee("Zara", 2020)
"创建 Employee 类的第二个对象"
emp2 = Employee("Manni", 2021)
使用点号 . 来访问对象的属性。使用如下类的名称访问类变量:
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)
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)
"创建 Employee 类的第一个对象"
emp1 = Employee("Zara", 2020)#Name : Zara , Salary: 2020
"创建 Employee 类的第二个对象"
emp2 = Employee("Manni", 2021)#Name : Manni , Salary: 2021
emp1.displayEmployee()
emp2.displayEmployee()
print("Total Employee %d" % Employee.empCount)#Total Employee 2
以添加,删除,修改类的属性,如下所示:
emp1.age = 7 # 添加一个 'age' 属性
emp1.age = 8 # 修改 'age' 属性
del emp1.age # 删除 'age' 属性
3、魔法方法
Python 的对象天生拥有一些神奇的方法,它们是面向对象的 Python 的一切…它们是可以给你的类增加魔力的特殊方法…如果对象实现了这些方法中的某一个,那么这个方法就会在特殊的情况下被 Python 所调用,而这一切都是自动发生的…
类有一个名为 init(self[, param1, param2…]) 的魔法方法,该方法在类实例化时会自动调用。
class Ball:
def __init__(self, name):
self.name = name
def kick(self):
print("我是%s,该死的,谁踢我..." % self.name)
a = Ball("足球")
b = Ball("足球B")
c = Ball("足球C")
a.kick()# 我是足球,该死的,谁踢我...
b.kick()# 我是足球B,该死的,谁踢我...
在 Python 中定义私有变量只需要在变量名或函数名前加上“__”两个下划线,那么这个函数或变量就会为私有的了。
class JustCounter:
__secretCount = 0 # 私有变量
publicCount = 0 # 公开变量
def count(self):
self.__secretCount += 1
self.publicCount += 1
print(self.__secretCount)
counter = JustCounter()
counter.count() # 1
counter.count() # 2
print(counter.publicCount) # 2
print(counter._JustCounter__secretCount) # 2 Python的私有为伪私有
print(counter.__secretCount)
# AttributeError: 'JustCounter' object has no attribute '__secretCount'