脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python面向对象之类和实例用法分析

Python面向对象之类和实例用法分析

2021-07-02 00:48feesland Python

这篇文章主要介绍了Python类和实例用法,较为详细的分析了Python面向对象程序设计中类、实例、构造函数、析构函数、私有变量等相关概念与使用技巧,需要的朋友可以参考下

本文实例讲述了python面向对象和实例用法。分享给大家供大家参考,具体如下:

虽然 python 是解释性语言,但是它是面向对象的,能够进行对象编程。至于何为面向对象,在此就不详说了。面向对象程序设计本身就很值得深入学习,如要了解,请参阅网上其他的资料。

面向对象最重要的概念就是类(class)和实例(instance),牢记 类 是抽象的模板,比如student类,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可能不同。

以student类为例,在python中,定义类是通过 class 关键字:

注意:python 2.x 需要在类名后面加 (object)  这边 pass 语句表示空语句段。

class 后面紧接着是类名,即student,类名通常是大写开头的单词,紧接着是(object),表示该类是从哪个类继承下来的,继承的概念我们后面再讲,通常,如果没有合适的继承类,就使用object类,这是所有类最终都会继承的类。

?
1
2
class student(object):
  pass

python 3.x 则只需要类名,不需要加 (object)

?
1
2
class student:
  pass

实例

创建实例是通过类名+()实现的(若 __init__ 无或仅有self);如定义好了student类,就可以根据student类创建出student的实例,如下:

?
1
2
3
4
class student(object):
  pass
may = student()          # 新建may实例
print(may)

运行结果:

<__main__.student object at 0x0000000001dcc400>

可以看到,变量may指向的就是一个student的object,后面的0x006c4770是内存地址,每个object的地址都不一样,而student本身则是一个类。

可以自由地给一个实例变量绑定属性,比如,给实例 may 绑定一个 name 属性,这个 name 属性是实例 may 特有的,其他新建的实例是没有 name 属性的

?
1
2
3
4
5
6
7
8
class student(object):
  pass
may = student()         # 新建may实例
print(may)
may.name = "may"         # 给实例 may 绑定 name 属性为 "may"
print(may.name)
peter = student()        # 新建peter实例
# print(peter.name)       # 报错,因为peter没有name属性

那么,如果我们需要类必须绑定属性,那如何定义呢?  请参见下文。

__init__ 构造函数

由于类可以起到模板的作用,因此,可以在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去。 (注意 __init__ 双下划线)

如对于student类,我们定义 name 和 score 属性(所有sudent 都须有的属性):

__init__方法的第一个参数永远是self,表示创建的实例本身,因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。

有了__init__方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数,但self不需要传,python解释器自己会把实例变量传进去:

?
1
2
3
4
5
6
7
8
class student(object):
  def __init__(self, name, score):
    self.name = name
    self.score = score
may = student("may",90)      # 须要提供两个属性
peter = student("peter",85)
print(may.name, may.score)
print(peter.name, peter.score)

__del__ 析构函数

just like the __init__ method, there is another special method __del__ which is called when an object is going to die i.e. it is no longer being used and is being returned to the computer system for reusing that piece of memory.

the __del__ method is run when the object is no longer in use and there is no guarantee when that method will be run. if you want to explicitly see it in action, we have to use the del statement which is what we have done here.

相对于 构造函数 python 也有类似 c++ 中的析构函数 __del__ , python的垃圾回收过程与常用语言的不一样,如果一定需要,最好需要使用del语句来激活。

私有变量

note for c++/java/c# programmers
all class members (including the data members) are public and all the methods are virtual in python.
one exception: if you use data members with names using the double underscore prefix such as __privatevar, python uses name-mangling to effectively make it a private variable.
thus, the convention followed is that any variable that is to be used only within the class or object should begin with an underscore and all other names are public and can be used by other classes/objects. remember that this is only a convention and is not enforced by python (except for the double underscore prefix).

python 中定义私有变量,命名规则为前缀加两个下划线 “__” ,注意不可前后都包含__xxx__(该命名表示为类属性或内建变量);还有一种命名为单下划线 _xxx ,表示约定俗成不可访问的变量。

?
1
2
3
4
5
6
7
8
9
10
11
12
class person(object):
  def __init__(self,name,sex):
    self.name = name
    self.__sex = sex       # sex 定义为私有变量
  def print_title(self):
    if self.sex == "male":
      print("man")
    elif self.sex == "female":
      print("woman")
may = person("may","female")
print(may.name)   
print(may.__sex)           # 会报错

希望本文所述对大家python程序设计有所帮助。

原文链接:https://www.cnblogs.com/feeland/p/4409130.html

延伸 · 阅读

精彩推荐