Python从入门到实战(一)——Python基础
Python从入门到实战(二)——程序流程控制
Python从入门到实战(三)——组合数据类型
Python从入门到实战(四)——函数
Python从入门到实战(五)——模块和包
Python从入门到实战(六)——文件
Python从入门到实战(七)——面向对象
Python从入门到实战(八)——异常
Python从入门到实战(九)——多线程
Python从入门到实战(十)——爬虫
文章目录
面向对象概念


每个颜色对应,名字,状态,操作。
类和对象

总的来说,类是抽象的,对象是具体的实例

class Myclass(object):
def infor(self):
print("this is a class")
类与对象实例
class Bird():
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print('Aaaah...')
self.hungry = False
else:
print('No,thanks!')



实例属性和类属性

class Car:
price = 100000 # 定义类属性
def __init__(self, c):
self.color = c # 定义实例属性
# 主程序
car1 = Car('Red')
car2 = Car('Blue')
print(car1.color, Car.price)
Car.price = 110000 # 修改类属性
Car.name = 'QQ' # 可以在类外增加类属性
car1.color = 'Yellow' # 修改实例属性
print(car2.color, Car.price, Car.name)
print(car1.color, Car.price, Car.name)

如果属性名以__(双下划线)开头则是私有属性,否则是公有属性。私有属性在类外不能直接访问。
但Python提供了访问私有属性的方式,可用于程序的测试和调试。
对象名._类名私有成员名
示例
class Food:
def __init__(self):
self.__color = 'red'
self.price = 10
apple = Food()
apple.price = 20
print(apple.price, apple._Food__color) # 访问私有成员
apple._Food__color = "Blue" # 修改私有成员
print(apple.price, apple._Food__color)
print(apple.__color) # 不能直接访问私有属性

所以,Python没有真正意义上的私有属性。
Python可以动态地添加和删除实例和类的属性。
class Point1:
cd1 = 1
def __init__(self):
self.pd1 = 2
print('Class Point1 created!')
# 在普通方法内,也可以用self增加实例属性
def testpd(self):
self.pd2 = 3
p1 = Point1()
p1.testpd()
print(p1.pd1)
print(p1.pd2)
p1.pd3 = 4 # 在类外可以用实例名增加实例属性
print(p1.cd1)
print(p1.__dict__.items()) #显示实例的属性
print(Point1.__dict__.items()) #显示类的属性即方法
del p1.pd3 # 删除p1实例的d3属性
print(p1.__dict__.items())
Point1.cd2 = 5
print(Point1.__dict__.items())

类属性和实例属性可以同名
类的方法

普通方法

class MyClass:
"""A simple example class"""
i = 12345
def f1(c): # 如果带了一个或多个参数,不管第一个参数是否叫self,都会被作为实例本身的引用,所以只能使用实例名加.的方式访问
return str(c) + 'hello world'
def f2(): # 如果没有带参数,只能使用类名加.的方式访问
return 'hehe'
classmethod

class MyClass:
"""A simple example class"""
i = 12345
@classmethod
def f1(c): # 带一个或多个参数时,第一个参数会作为类本身的引用,所以能用实例名加.的方式调用,也能使用类名加.的方式调用
return str(c) + 'hello world'
@classmethod
def f2(): # 加了@classmethod的方法,至少要有一个参数,不然没有意义,被调用时会报错
return 'hehe'

staticmethod

class MyClass:
"""A simple example class"""
i = 12345
@staticmethod
def f1(c): # 加了@staticmethod的方法,和最普通的类外函数一样,参数也是作为普通参数看待,不代表类也不代表实例,所以能用实例名加.的方式调用,也能使用类名加.的方式调用
return str(c) + 'hello world'
@staticmethod
def f2():
return 'hehe'

私有方法
双下划线__开头的方法称为私有方法。
class Fruit:
price = 0
def __init__(self):
self.__color = 'Red' # 定义和设置私有属性color
self.__city = 'Kunming' # 定义和设置私有属性city
def __outputColor(self): # 定义私有方法outputColor
print(self.__color) # 访问私有属性color
def __outputCity(self): # 定义私有方法outputCity
print(self.__city)
def output(self): # 定义公有方法output
self.__outputColor() # 调用私有方法outputColor
self.__outputCity() # 调用私有方法outputCity
@ staticmethod
def getPrice(): # 定义静态方法getPrice
return Fruit.price
@ staticmethod # 定义静态方法setPrice
def setPrice(p):
Fruit.price = p
# 主程序
apple = Fruit()
apple.output()
print(Fruit.getPrice())
Fruit.setPrice(9)
print(Fruit.getPrice())

构造函数与析构函数
构造函数


class Student(object):
def __init__(self, first='', last='', id=0):
self.firstnamestr = first
self.lastnamestr = last
self.idint = id
s1 = Student()
print(s1.firstnamestr)
s2 = Student(last='Python',first='Hello')
print(s2.lastnamestr)


析构函数

class Car:
def __init__(self, n):
self.num = n
print('编号为', self.num, '的对象出生了')
def __del__(self):
print('编号为', self.num, '的对象死了')
car1 = Car(1)
def func():
car2 = Car(2)
del car1
func() # 函数结束会释放内存

__str__方法
__str__方法可以在访问实例的时候调用。

namedtuple函数
collections模块提供的namedtuple函数,可以很方便地创建类,并且属性可以用下标的方式访问。

运算符的重载


class Number:
def __init__(self, start):
self.data = start
def __sub__(self,other):
return Number(self.data - other.data)
x = Number(5)
y = Number(2)
z = x - y
z.data

重载方法举例

class Index:
def __getitem__(self, index):
return index
def __setitem__(self, index, value):
pass
x = Index()
print(x[3])
for i in range(6):
print(x[i], end=' ')


class Stepper:
def __init__(self,s):
self.data = s
def __getitem__(self, i):
return self.data[i]
x = Stepper('spam')
print(x[1])
for item in x:
print(item, end = ' ')


class Squares:
def __init__(self, start, stop):
self.value = start - 1
self.stop = stop
def __iter__(self):
return self
def __next__(self):
if self.value == self.stop:
raise StopIteration
else:
self.value += 1
return self.value**2
sq = Squares(1,5)
for i in sq:
print(i, end=' ')


继承
单继承

父类
class Super:
def method(self):
print('in Super.method')
子类
class Sub(Super):
def method(self): # 重写父类method方法
print('starting Sub.method')
Super.method(self)
print('ending Sub.method')

继承(也称为派生)的主要目的是功能扩展和更新

父类
class Person(object):
def __init__(self,name,sex):
self.name = name
self.sex = sex
def print_title(self):
print(self.name, self.sex)
子类
class Adult(Person):
def __init__(self, name, sex, job):
super().__init__(name, sex)
self.job = job
def print_job(self):
super().print_title()
print('I am', self.name)
print('I am a',self.job)

多继承
子类有多个父类,并且具有他们的特征
父类A
# 父类A
class A:
def printA(self):
print('----A----')
父类B
# 父类B
class B:
def printB(self):
print('----B----')
子类C,继承A,B
# 定义一个子类,继承自A、B
class C(A, B):
def printC(self):
print('----C----')

本文详细介绍Python面向对象编程的基础知识,包括类与对象的概念、实例属性与类属性的区别、方法的种类(如普通方法、类方法、静态方法)、私有属性与方法的实现方式,以及构造函数、析构函数和__str__方法的使用。此外还介绍了如何通过继承来扩展类的功能。
608

被折叠的 条评论
为什么被折叠?



