可以使用as给模块内的方法或者类起别名:
# You can shorten module namesimport math as mmath.sqrt(16) == m.sqrt(16)# => True复制代码
我们可以使用dir查看我们用的模块的路径:
# You can find out which functions and attributes# are defined in a module.import mathdir(math)复制代码
这么做的原因是如果我们当前的路径下也有一个叫做math的Python文件,那么会覆盖系统自带的math的模块 。这是尤其需要注意的,不小心会导致很多奇怪的bug 。
类我们来看一个完整的类,相关的介绍都在注释当中
# We use the "class" statement to create a classclass Human:# A class attribute. It is shared by all instances of this class# 类属性,可以直接通过Human.species调用,而不需要通过实例species = "H. sapiens"# Basic initializer, this is called when this class is instantiated.# Note that the double leading and trailing underscores denote objects# or attributes that are used by Python but that live in user-controlled# namespaces. Methods(or objects or attributes) like: __init__, __str__,# __repr__ etc. are called special methods (or sometimes called dunder methods)# You should not invent such names on your own.# 最基础的构造函数# 加了下划线的函数和变量表示不应该被用户使用,其中双下划线的函数或者是变量将不会被子类覆盖# 前后都有双下划线的函数和属性是类当中的特殊属性def __init__(self, name):# Assign the argument to the instance's name attributeself.name = name# Initialize propertyself._age = 0# An instance method. All methods take "self" as the first argument# 类中的函数,所有实例可以调用,第一个参数必须是self# self表示实例的引用def say(self, msg):print("{name}: {message}".format(name=self.name, message=msg))# Another instance methoddef sing(self):return 'yo... yo... microphone check... one two... one two...'# A class method is shared among all instances# They are called with the calling class as the first argument@classmethod# 加上了注解,表示是类函数# 通过Human.get_species来调用,所有实例共享def get_species(cls):return cls.species# A static method is called without a class or instance reference@staticmethod# 静态函数,通过类名或者是实例都可以调用def grunt():return "*grunt*"# A property is just like a getter.# It turns the method age() into an read-only attribute of the same name.# There's no need to write trivial getters and setters in Python, though.@property# property注解,类似于get,set方法# 效率很低,除非必要,不要使用def age(self):return self._age# This allows the property to be set@age.setterdef age(self, age):self._age = age# This allows the property to be deleted@age.deleterdef age(self):del self._age
以上内容的详细介绍之前也有过相关文章,可以查看:
Python——slots,property和对象命名规范
下面我们来看看Python当中类的使用:
# When a Python interpreter reads a source file it executes all its code.# This __name__ check makes sure this code block is only executed when this# module is the main program.# 这个是main函数也是整个程序入口的惯用写法if __name__ == '__main__':# Instantiate a class# 实例化一个类,获取类的对象i = Human(name="Ian")# 执行say方法i.say("hi")# "Ian: hi"j = Human("Joel")j.say("hello")# "Joel: hello"# i和j都是Human的实例,都称作是Human类的对象# i and j are instances of type Human, or in other words: they are Human objects# Call our class method# 类属性被所有实例共享,一旦修改全部生效i.say(i.get_species())# "Ian: H. sapiens"# Change the shared attributeHuman.species = "H. neanderthalensis"i.say(i.get_species())# => "Ian: H. neanderthalensis"j.say(j.get_species())# => "Joel: H. neanderthalensis"# 通过类名调用静态方法# Call the static methodprint(Human.grunt())# => "*grunt*"# Cannot call static method with instance of object# because i.grunt() will automatically put "self" (the object i) as an argument# 不能通过对象调用静态方法,因为对象会传入self实例,会导致不匹配print(i.grunt())# => TypeError: grunt() takes 0 positional arguments but 1 was given# Update the property for this instance# 实例级别的属性是独立的,各个对象各自拥有,修改不会影响其他对象内的值i.age = 42# Get the propertyi.say(i.age)# => "Ian: 42"j.say(j.age)# => "Joel: 0"# Delete the propertydel i.age# i.age# => this would raise an AttributeError
这里解释一下,实例和对象可以理解成一个概念,实例的英文是instance,对象的英文是object 。都是指类经过实例化之后得到的对象 。
推荐阅读
- 详解 Python 的二元算术运算,为什么说减法只是语法糖?
- 雷达模拟:用python的pygame实现和代码分析
- 如何实现一个优雅的Python的Json序列化库
- 教你在几分钟内构建一个Python包
- Mac 上安装 pyenv 使用多版本python开发项目
- 微信群总是有人发广告?看我用Python写一个机器人消灭他
- 用Python实现多层感知器神经网络
- Python 中的数字到底是什么?
- 如何建立一个完美的 Python 项目
- 用python制作炫酷的滚动地球