您的位置:首页 > 编程语言 > Python开发

python入门系列:面向对象

2019-02-13 15:22 363 查看

类和对象的创建

经典类 没有继承 object的类

新式类 继承了 object的类

class Money: # 2.x中默认是经典类,3.x中是新式类
pass

class Money(object): # 兼容的一种写法
pass

Money既是类的name属性名,又是一个引用该类的变量

print(Money.name) # Money
xxx = Money
print(xxx.name) # Money
对象

one = Money()
print(one) # <main.Money object at 0x000001555E9534A8>
print(one.class) # <class 'main.Money'>
属性相关

对象属性

class Person:
pass
p = Person()

给 p对象增加属性, 所有的属性是以字典的形式组织的

p.age = 18
print(p.age) # 18
print(p.dict) # {'age': 18}
print(p.sex) # AttributeError: 'Person' object has no attribute 'sex'

删除p对象的属性

del p.age
print(p.age) # AttributeError: 'Person' object has no attribute 'age'
类属性

class Money:
num = 666
count = 1
type = "rmb"

print(Money.num) # 666

对象查找属性,先到对象自身去找,若未找到,根据 class找到对应的类,然后去类中查找

one = Money()
print(one.count) # 1

不能通过对象去 修改/删除 对应类的属性

one.num = 555 # 实际上是给 one 对象增加了一个属性
print(Money.num) # 666
print(one.num) # 555

类属性会被各个对象共享

two = Money()
print(one.num, two.num) # 666 666
Money.num = 555
print(one.num, two.num) # 555 555
限制对象的属性添加

类中的 slots属性定义了对象可以添加的所有属性

class Person:
slots = ["age"] # 只允许添加一个 age属性

p1 = Person()
p1.age = 1
p1.num = 2 # AttributeError: 'Person' object has no attribute 'num'
私有化属性

Python没有真正的私有化支持,只能用给变量添加下划线来实现伪私有;通过名字重整机制
属性的访问范围:类的内部-->子类内部-->模块内的其他位置-->其他模块
公有属性 x 的访问范围

类的内部
子类内部
模块内的其他位置
子类内部
受保护属性 _x 的访问范围

类的内部
子类内部
模块内的其他位置(但不推荐)
子类内部(from ... import xxx 不可以访问,要指明all变量)
私有属性 __x 的访问范围

类的内部
子类内部
模块内的其他位置
子类内部(同_x)
保护数据案例

class Person:
def init(self):
self.__age = 18

def set_age(self, age): # 错误数据的过滤
if isinstance(age, int) and 0 < age < 150:
self.__age = age
else:
print("Wrong age value")

def get_age():
return self.__age

p = Person()
print(p.get_age()) # 18
p.set_age(22)
print(p.get_age()) # 22
只读属性

1. 属性私有化 + 属性化 get()方法

class Person(object):
def init(self):
self.__age = 18

可以以使用属性的方式来使用方法

@property
def age(self):
return self.__age
p = Person()
print(p.age) # 18
p.age = 666 # Attribute Error: can't set attribute

2. 通过底层的一些函数

class Person:

通过 属性 = 值 的方式来给一个对象增加属性时,底层都会调用这个方法,构成键值对,存储在 dict字典中

可以考虑重写底层的这个函数,达到只读属性的目的

def setattr(self, key, value):
if key == "age" and key in dict:
print("read only attribute")
else:
self.dict[key] = value
方法相关

方法的划分

实例方法
类方法
静态方法
class Person:
def instance_fun(self): # self: 调用对象的本身,调用时不用写,解释器会传参
print("instance method", self)

@classmethod
def class_fun(cls): # cls: 类本身
print("class method", cls)

@staticmethod
def static_fun():
print("static method")
所有的方法都存储在类中,实例中不存储方法
类方法和静态方法无法访问实例属性
方法的私有化

和变量的私有化思想差不多
class Person:
__age = 18

def __run(self): # 只能在该类中被调用
print("running...")
元类

创建类对象的类(类也是一个对象)
a, s = 8, "123"
print(a.class, s.class) # <class 'int'> <class 'str'>
print(int.class, str.class) # <class 'type'> <class 'type'>
type是元类。

通过type元类来创建类,动态创建。也可以用metaclass来指明元类,进行类的创建。
检测类对象中是否有 metaclass属性
检测父类中是否有 metaclass属性
检测模块中是否有 metaclass属性
通过内置的type来创建类
def run(self):
print("run...")

Dog = type("Dog", (), {"count": 0, "run": run})
print(Dog) #
d = Dog()
print(d.count) # 0
print(d.run()) # run...
更加详细的内容,在进高级部分的元类编程讲解

内置的特殊属性

内置的特殊方法(魔法函数)

这里只做一个了解,高级部分会详细地讲解魔法函数。可以理解为在类中实现了这些特殊的函数,类产生的对象可以具有神奇的语法效果。

信息格式化操作

calss Person:
def init(self, n, a):
self.name = n
self.age = a

面向用户

def str(self):
return "name: %s, age: %d" % (self.name, self.age)

面向开发人员

def repr(self):

todo

一般默认给出对象的类型及地址信息等

打印或进行格式转换时,先调用 str()函数,若未实现,再调用 repr()函数

p = Person("Rity", 18)
print(p) # name: Rity, age: 18
res = str(p)
print(res) # name: Rity, age: 18
print(repr(p)) # <main.Person object at 0x000001A869BEB470>
调用操作

使得一个对象可以像函数一样被调用

class PenFactory:
def init(self, type):
self.type = type

def call(self, color):
print("get a new %s, its color is %s" % (self.type, color))

pencil = PenFactory("pencil")
pen = PenFactory("pen")

一下两种使用方式会调用 call()函数

pencil("red") # get a new pencil, ites color is red
pencil("blue") # get a new pencil, ites color is blue
pen("black") # get a new pen, ites color is black
索引操作

class Person:
def init(self):
self.cache = {}

def setitem(self, key, value):
self.cache[key] = value

def getitem(self, key):
return self.cache[key]

def delitem(self, key):
del self.cache[key]

p = Person()
p["name"] = "MetaTian"
...
比较操作

使得自己定义的类可以按照一定的规则进行比较

[p]import functools[url=mailto:br/>@functools.total_ordering@functools.total_ordering
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python python入门