Python基础笔记(五)
1. 类(class)
下面的代码建立了一个Employee类:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Employee(object):
company = "IBM"
def __init__(self, name, sex, age, salary):
self.name = name
self.sex = sex
self.age = age
self.__salary = salary
def getSignature(self):
signature = "My name is %s, I'm %d years old." % (self.name, self.age)
return signature
def getSalary(self):
return self.__salary
def setSalary(self, salary):
if 0 < salary <= 10000:
self.__salary = salary
else:
raise ValueError("Invalid Value")
tom = Employee("tom", "male", 23, 3000)
print(tom.getSignature())
# My name is tom, I'm 23 years old.
print(tom.age)
# 23
tom.setSalary(5000)
tom.__salary = 9000 # 无效,其实是新增了一个名为"__salary"的变量
print(tom.getSalary())
# 5000
__init__
方法相当于其它语言的“构造函数”,该方法的第一个参数必须为self,self代表创建的实例本身,因此在__init__
方法内部可以把各种属性绑定到self;在实际调用时,self并不需要传递,Python解释器自己会把实例变量传进去。
以一个下划线开头的变量名,例如_company
,这种变量外部是可以访问的,但是按照约定俗成的规定,这种变量应该视为私有变量,不要随意访问。
以两个下划线开头的变量名,例如__salary
,是私有变量,外部不能直接访问,一般提供"get"和"set"方法去间接获取和修改。
开头与结尾都是两个下划线,例如__name__
,是特殊变量,特殊变量是可以直接访问的。
需要注意的是,当在一个外部类尝试用下面的代码访问新建的Employee类时,是会报错的:
import Employee
tom = Employee("tom", "female", "23")
报错内容为TypeError: 'module' object is not callable
,这个错误是指试图把模块作为一个函数来调用。产生错误的原因是,import Emplyee
其实是导入了整个的Employee.py
,而不是名为Employee
的类。正确的做法有两种:
(1) 用“模块名.类名“来访问:
import Employee
tom = Employee.Employee("tom", "male", 23, 6000)
(2) 用"from...import..."的形式导入
from Employee import *
tom = Employee("tom", "male", 23, 6000)
2. 获取对象的类型
type(obj)
函数返回参数的对象类型,基本类型如int
和str
也可以用它来判断:
from Employee import *
tom = Employee("tom", "male", 23, 6000)
print(type(23))
# <class 'int'>
print(type("ABC"))
# <class 'str'>
print(type(tom))
# <class 'Employee.Employee'>
if type(123) == type(456):
print("Equal")
if type("ABC") == str:
print("Equal")
print(type(tom) == Employee)
# True
可以使用types模块中定义的常量来判断一个对象是否是函数,lambda函数或generator:
import types
def myFun():
pass
# 是否是函数
print(type(myFun) == types.FunctionType)
# True
# 是否是内置函数
print(type(abs) == types.BuiltinFunctionType)
# True
# 是否是lambda函数
print(type(lambda x: x)==types.LambdaType)
# True
# 是否是generator
print(type((x for x in range(10)))==types.GeneratorType)
# True
能用type()判断的基本类型也可以用isinstance()判断:
print(isinstance(23,int))
# True
print(isinstance("ABC", str))
# True
print(isinstance(b"A", bytes))
# True
print(isinstance(tom, Employee))
# True
isinstance()还可以用于判断一个对象是否是某些类型中的一种:
print(isinstance("23", (str, int)))
# True
print(isinstance([1, 2, 3], (list, tuple)))
# True
3. 获取对象的属性和方法
如果要获得一个对象的所有属性和方法,可以使用dir(obj)
函数,它返回一个包含字符串的list
print(dir("ABC"))
# ['__add__', '__class__', ... , 'upper', 'zfill']
类似__xxx__的属性和方法在Python中都是有特殊用途的,比如__len__方法返回长度。在Python中,如果你调用len()函数试图获取一个对象的长度,实际上,在len()函数内部,它自动去调用该对象的__len__()方法,所以,下面的代码是等价的:
print(len("ABC"))
print("ABC".__len__())
下面的例子证明了len()会调用__len__()方法:
class MyClass1(object):
def __len__(self):
return 100
class MyClass2(object):
pass
myClass = MyClass1()
print(len(myClass))
# 100
myClass = MyClass2()
print(len(myClass))
# TypeError: object of type 'MyClass2' has no len()
4. hasattr、getattr和setattr
利用这三个方法,可以判断对象是否有某属性/方法,获取指定名称的属性/方法,新增属性等操作:
class Employee(object):
def __init__(self, name, sex, age, salary):
self.name = name
self.sex = sex
self.age = age
self.__salary = salary
def getSignature(self):
signature = "My name is %s, I'm %d years old." % (self.name, self.age)
return signature
employee = Employee("tom", "male", 23, 3000)
# 判断对象是否有"age"属性,有则打印并赋值
if hasattr(employee, "age"):
print(employee.age)
employee.age = 18
# 如果对象没有"hobby"属性,则新增该属性并赋值
if not hasattr(employee, "hobby"):
setattr(employee, "hobby", "music")
# 通过getattr获取对象指定的属性值
print(getattr(employee, "hobby"))
# music
# 如果试图获取不存在的属性,会抛出AttributeError的错误:
# getattr(employee, "gold")
# AttributeError: 'Employee' object has no attribute 'gold'
# 利用getattr的第三个参数:如果属性不存在,就返回一个默认值
print(getattr(employee, "gold", "not exist"))
# not exist
# 通过getattr获取方法,注意:如果方法不存在,会抛出AttributeError
print(getattr(employee, "getSignature"))
# <bound method Employee.getSalary of <__main__.Employee object at 0x10832a4a8>>
# 判断是否存在指定名称的方法,如果存在,则执行该方法
try:
funcName = "getSignature"
func = getattr(employee, funcName)
if hasattr(func, "__call__"):
print("存在方法", funcName)
# 存在方法 getSignature
print(func())
# My name is tom, I'm 18 years old.
except AttributeError as e:
print("没有方法:", funcName)
Python基础笔记(五)的更多相关文章
- Python基础笔记系列十一:标准输入输出、文件读写和指针等操作
本系列教程供个人学习笔记使用,如果您要浏览可能需要其它编程语言基础(如C语言),why?因为我写得烂啊,只有我自己看得懂!! 标准输入输出一.输入 在sublime中这个时候需要安装SublimeRE ...
- Python基础笔记系列一:基本工具与表达式
本系列教程供个人学习笔记使用,如果您要浏览可能需要其它编程语言基础(如C语言),why?因为我写得烂啊,只有我自己看得懂!! 工具基础(Windows系统下)传送门:Python基础笔记系列四:工具的 ...
- Python基础学习五
Python基础学习五 迭代 for x in 变量: 其中变量可以是字符串.列表.字典.集合. 当迭代字典时,通过字典的内置函数value()可以迭代出值:通过字典的内置函数items()可以迭代出 ...
- 我的Python基础笔记
Python是从刚开始参加工作,就有听各方面的测试大牛推崇,但是刚开始做测试时还是把基础的测试方法放在第一位来学习的,直到半年多以后才开始接触Python. 我的Python基础主要是以廖雪峰老师的在 ...
- Python基础知识(五)------字典
Python基础知识(四)------字典 字典 一丶什么是字典 dict关键字 , 以 {} 表示, 以key:value形式保存数据 ,每个逗号分隔 键: 必须是可哈希,(不可变的数据类型 ...
- Python基础笔记1
这篇笔记来自廖雪峰的Python教程. 一.Python基础 Python使用缩进来组织代码块,务必遵守约定俗成的习惯,坚持使用4个空格的缩进. 在文本编辑器中,需要设置把Tab自动转换为4个空格,确 ...
- python基础笔记-0
python中数据结构,主要有列表.元组.字典.集合. python中最基本数据结构是序列(sequence).序列中每个元素被分配一个序号——即元素位置,也成为索引.第一个索引是0,第二个是1,以此 ...
- Python基础笔记系列五:元组
本系列教程供个人学习笔记使用,如果您要浏览可能需要其它编程语言基础(如C语言),why?因为我写得烂啊,只有我自己看得懂!! 元组 1)元组的结构和访问.使用方法和列表基本一致,区别主要有两点:1.使 ...
- python学习笔记五 模块下(基础篇)
shevle 模块 扩展pickle模块... 1.潜在的陷进 >>> import shelve>>> s = shelve.open("nb" ...
随机推荐
- javaEE复习重点个人总结
最近在学院或集队的群里看见最多的就是求javaEE大作业了,那么突然有感而发,写点参考性的期末复习总结. 第一章JavaEE 概述: 1:两层体系应用体系结构 安全性低,部署困难,消耗系统资源 2 三 ...
- iOS编程
一.语法 1. performSelector 2.
- SqlServer数据库优化之索引、临时表
问题:工作是查询一张500万多条数据的表时,查询总是很慢,于是进行优化. --查询表所有索引 use RYTreasureDB EXEC Sp_helpindex [RecordDrawScore] ...
- C++ OpenSSL 之一:编译和使用
1.官网 https://www.openssl.org/ 当前使用版本为OpenSSL 1.1.1c 2.编译 ①下载后解压,假设解压位置为/home/openssl-1.1.1c ②./confi ...
- frameset frame 页面空白
<html style="background:#213039;"> <head> <title>网站后台管理中心</title> ...
- Linux操作系统安全-使用gpg实现对称加密
Linux操作系统安全-使用gpg实现对称加密 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.gpg工具包概述 1>.什么是gpg GnuPG是GNU负责安全通信和数据存 ...
- LeetCode 1213. Intersection of Three Sorted Arrays
原题链接在这里:https://leetcode.com/problems/intersection-of-three-sorted-arrays/ 题目: Given three integer a ...
- Layui 关闭当前标签页
parent.layui.admin.events.closeThisTabs();
- 无旋treap大法好
无旋Treap大法好 原理? 是一棵二叉查找树: 一个节点左子树权值都比他小,右子树权值都比他大 所以可以维护序列(以位置为权值),或数值(以数值为权值) 是一个堆: 每个节点除了上述提到的权值外,还 ...
- CSS选择器分类整理
读完<CSS权威指南>,对选择器有如下整理: selector 本质上是执行元素样式匹配规则,我们可以利用它来限定某些元素 选择器类型: <!-- 实体,即HTML中存在 --> ...