面向对象(Java,Python)中Object,Class,Instance区别?(转载)
🏘️

面向对象(Java,Python)中Object,Class,Instance区别?(转载)

Tags
Python
Object
Published
August 18, 2021
Author
Eironn Walker
Class是一个模版,一个蓝图文件,用来描述具有通用属性的对象(Object)的描述文件(数据以及方法)。 Object和Instance本质上是一样的含义,指的都是通过模版(Class)初始化的实例/对象。只是在不同场景可能选择不同用词(Instance更具体化一些)。

书中的定义

Object-Oriented Software Engineering 这本书中对于这三个名次的定义:
  • Object:An object is characterized by a number of operations and a state which remembers the effect of these operations.(p.44)
  • Class:A class represents a template for several objects and describes how these objects are structured internally. Objects of the same class have the same definition both for their operations and for their information structures.(p.50)
  • Instance:An instances an object created from a class. The class describes the (behavior and information)structure of the instance, while the current state of the instance is defined by the operations performed on the instance.(p.50)

网友的解释一

class is a blueprint which you use to create objects. An object is an instance of a class - it's a concrete 'thing' that you made using a specific class. So, 'object' and 'instance' are the same thing, but the word 'instance' indicates the relationship of an object to its class.
This is easy to understand if you look at an example. For example, suppose you have a class House. Your own house is an object and is an instance of class House. Your sister's house is another object (another instance of class House).
// Class House describes what a house is class House { // ... } // You can use class House to create objects (instances of class House) House myHouse = new House(); House sistersHouse = new House();
The class House describes the concept of what a house is, and there are specific, concrete houses which are objects and instances of class House.
Note: This is exactly the same in Java as in all object oriented programming languages.

网友的解释二

  • Class是用来定义object的一种东西,class的内容包含了动作(operations)与资料(data)。
  • 动作(operations)、方法(methods)和行为(behaviors)可以看作同义词。理想上一个object的状态只能透过动作去改变它。
  • 一个object就是某个class的instance,换句话说可以把object和instance看作是同样的东西。只是在某些场合大家比较习惯用object这个说法,其他场合则是会用instance。

参考文章