I am a self-taught python user (kind of.). I read much to deepen my knowledge about python. Today
I encountered a text saying:
... classes and objects ....
So I was wondering what is the difference between objects and classes in python. I taught all classes are objects, but in that case, author wouldn't have used phrase "classes and objects". I'm confused...
These are two closely related terms in object oriented programming. The standard meaning is that an object is an instance of a class.
An object is an instantiation of a class.
Think of a class like the blueprint of a car.
Ford make cars (objects) based on the rules and information enclosed in the blueprint.
Yes, classes (and functions, and modules, and basically everything) in Python are objects, too. The difference lies in their types:
class Foo(object): pass
print type(Foo)
print type(Foo())
To see they're both objects, you can check that they both have attributes:
print dir(Foo)
print dir(Foo())
A class describes what that object will be, but it isn't the object itself.
A class is an idea. An object is the fruition of that idea.
Related
i am learning UML and I need some clarity about class diagrams.
for example I have the class
person with firstname, surname, date of birth as attributes.
what are or is the object? i do understand the class (that is person including the attributes), i do understand the attributes. but they are also talking about objects in my book, what would that be?
thank you in advance.
Where to start? Not that easy. Trying to find the definition of Class in UML 2.5 PDF is like looking for something in the remains of the Twin towers after 9/11 :-( So I took the UML metamodel published by OMG as XMI and imported that into EA. And there were are:
Class
You find the element like this:
and it's comment reads
A Class classifies a set of objects and specifies the features that characterize the structure and behavior of those objects. A Class may have an internal structure and Ports.
So, as it looks, a Class is derived from objects. Pretty much what Carl Linnaeus did in the 18th century. We can leave that for the moment and start looking for those objects.
Object
Trying to look for an Object element in the metamodel revealed: nothing. Probably for good reason since it's going into metaphysics. And Carl from above wasn't the only guy thinking about classification of the world.
Side note: I created an instance of Class in EA and ended up with an element of the metatype Object. A relic from pre UML 2.0 times. I looked into UML 1.5 and actually found a definition of object on p. 3-64:
3.39 Object
3.39.1 Semantics
An object represents a particular instance of a class. It has identity and attribute values. A similar notation also represents a role within a collaboration because roles have instance-like characteristics.
This has settled for a long time and is still in the mindset of most people. The IT guys defined a couple of classes out of the blue (with some requirements in mind) and when you use them you have these objects. Quite the other way around our Carl was approaching things. And now 12 years after UML 1.5 we have UML 2.5 and no trace of Object!
So, per UML 2.5 an Object does not exist. But we have ObjectFlow and ObjectNodes. So there must be something. On p. 12 of UML 2.5 you find
6.3 On the Semantics of UML
6.3.1 Models and What They Model
Classifiers. A classifier describes a set of objects. An object is an individual with a state and relationships to other objects. The state of an object identifies the values for that object of properties of the classifier of the object. (In some cases, a classifier itself may also be considered an individual; for example, see the discussion of static structural features in sub clause 9.4.3.)
and a bit below
UML models do not contain objects, occurrences, or executions, because such individuals are part of the domain being modeled, not the content of the models themselves. UML does have modeling constructs for directly modeling individuals: instance specifications, occurrence specifications, and execution specifications for modeling objects, occurrences, and executions, respectively, within a particular context.
Honestly I was surprised to read that, since I still live in the past where we had object diagrams (UML tools like EA still allow to create them). And that's probably the cause of the confusion. An object is by far too complex (and it has been in discussion since the invention of philosophy) to end up as UML element. Instead, UML allows to bring light to certain aspects of an object by using e.g. SDs to see details of behavior.
Summary
It's a bit of the hen and egg problem. Mapping between real world (the "Objects") and what has been modeled (the "Class") is tough. And it depends on your goals. Are you trying to get your head around somehing that already exists and sketch its behavior or is it that you have invented something new where you want to see how it interacts?
In any case, your question, so simple it is, turns out to be an excellent one!
I like qwerty_so's well documented and comprehensive answer. May I suggest an intuitive alternative?
A class describes features of the objects that belong to the class. For example, the class Person defines firstname, surname, dateOfBirth as properties. It also defines the type of these properties.
Object of the class Person, say John:Person or Jane:Person have specific values for each of the properties. The object John would have firstname="John", lastname="Doe", dateOfBirth=1961-10-01, whereas the object Jane would have firstname="Jane", lastname="Smith",dateOfBirth=1965-02-20.
The same difference can be experimented with in popular programming languages. Example:
// definition of a class, i.e. the general rules
class Person {
private String firstname;
private String lastname;
...
public Person (String first, String last, ...) { ... }
public void doSomething() { ... }
}
// definition of objects, that abide by the classe's rules:
Person Jane = new Person("Jane", "Smith", ...);
Person P2 = new Person("John", "Doe", ...);
// the objects need to have their properties set. But the behaviors of the class can be used without redefining them
Jane.doSomething();
At my OOP theory exam I was asked a question "What is a metaclass? What is a metaclass of metaclass?". I answered first one easily, but have no idea about the second one. Is there even something like "metaclasses of metaclasses" in any programming language, or even theoritically? I tried implementing something like that in Python 3, but it seems it's a bit too complicated for my (I only had simple Python course for 1 semester).
Yes.
I will use the Python language to explain how can that be - maybe it is the language where metaclasses are more palpable (at least it is the language with the majority of questions involving metaclasses here).
So, in an OOP language where "classes" are first class objects - that is, they are themselves objects, and all the rules that apply to other objects apply to classes as well - they just happen to be the "template" for other kind of objects, these classes themselves are instances of "something". This something is the "metaclass" - which is just a word to designate the "class of a class".
And it happens that this "metaclass", the class of a class is an object as well, just as other classes. And as such, it also is an instance of a class - this class of the metaclass is what can be named the "metametaclass".
Now, bringing it down to a concrete example in Python - by default, the metaclass for classes in Python is type. That is, type is the class which instances are classes.
The language does have ingenious mechanisms that make it practical in some points to inherit a class from type, and then work with custom meta-classes.
So, what is the class of type? That will be the "metametaclass" for most (or all) classes in Python.
And as it goes, the class of "type" is "type" itself. yes - it is a circular reference, without which the object hierarchy of the language could not be bootstraped. I don't know if other languages do that differently - but in Python it is quite patent:
>>> class A:
... pass
...
>>> type(A)
<class 'type'>
>>> type(type(A))
<class 'type'>
>>> type(type(A)) is type(A)
True
Now, besides working like that as a concept, it actually can be used as a metametaclass, and there are mechanisms of the language that can be tweaked by inheriting type for that purpose. (Normally it will be inherited to be customized as an "ordinary" metaclass).
By coincidence, I had an use case for the "metametaclass" exemplified this very week, in a question here - by customizing Python's type __call__ method, instead of __new__ or __init__, and using this custom class as the "metaclass for a metaclass" one can actually control how those methods are called and the parameters passed to them methods when an ordinary class is be created.
I have class Controller in my java project, which has method like this:
As you can see, in the first line I am getting Singleton instance of ActualModes class and call method getActualModes().
So the first question is, which relatinship I should use in class diagram.
After that I am creating new instane of ModeContext class and then call method executeStrategy. In this case, which relatiship is better ?
It should be like this:
Access to the singleton (note the stereotype which is just convenient and no obligation or general standard) is anonymous and so you just have a dependency. The ModeContext in contrast uses a private (I don't know the scoping rules of the language you used, so I made it pivate) property called context. Note the dot which is saying exactly that.
Disclaimer: UML does not specify a mapping between Java and UML, so every answer to your question is open for debate.
I think both relationships are dependencies, drawn as dashed arrows from Controller to ActualModes and from Controller to ModeContext. The definition of 'dependency' according to the UML 2.5 specification (§7.8.4.1) is:
A Dependency is a Relationship that signifies that a single model Element or a set of model Elements requires other
model Elements for their specification or implementation.
An example of a type of relationship which is in my opinion less suited, is the association, although its definition (§11.5) is quite broad:
An Association classifies a set of tuples representing links between typed instances. (...) An Association specifies a semantic relationship that can occur between typed instances.
One could argue that there are links between Controller and the other two classes, in the form of variables, but these variables are local method variables, which exist only temporarily during the execution of the method. Associations represent more durable links, e.g. class members - as far as I understand UML and as far as I have seen associations used in practice.
I know there are some related questions about this question, such as this, this and this, but no one of them really helped me. My array keys are dynamic, so I can't create an additional class holding this attributes (like done in second linked question).
The idea of my concept is to hold instances of classes as follows:
$instances = [
"nameOfClass" => [
//instances of "nameOfClass"
],
"nameOfClass2" => [
//instances of "nameOfClass2"
]
//some more classes
];
But I don't know how to model these concept with UML when the array-key is unanimously with the class-name.
Is there a way to model my concept/in general associative arrays?
The correct way to express this in UML is to use a qualifier, or qualified association. There you have an owner and that has a qualifier, i.e., "key", that associates to a class. Further you can give the qualifier a type, to express that your key is a String, int, or Object of a certain class.
See also p. 206 of UML 2.5.
It sounds like you are wanting to simulate classes in PHP by building an associative array of named classes, where each class name (e.g., Person or ShoppingCart) maps to a collection of instances. If so, you are essentially trying to represent a non-OO simulation of OO in UML. UML is already OO, so you are trying to jump through your own belly button!
Unlike in PHP, in UML, a Property (i.e., a variable) must be owned by a Classifier, which is usually a Class or an Association. Therefore, to express $instances as a Property, it would have to be owned by a Class or Association.
If you are willing to accept that there will be an owning Class (let's call it ClassIndex), you will then need another UML Class, probably called Class, to represent each class (e.g., Person or ShoppingCart) and its attributes (e.g., firstName and lastName). Are you getting confused by the meta-programming yet? We haven't even gotten to the part about how to track the attributes of each class and so on.
While UML has all of the parts you need to re-invent OO programming, you have a fundamental mismatch between UML and PHP. The same would be true for C or assembler. UML allows you to work at a much higher level of abstraction than those languages. Therefore, I recommend you get an OO simulation working, then use UML to model your domain classes (e.g., Person or ShoppingCart) and generate a "configuration" that your OO simulation can run.
In a UML diagram when you create an instance of a subclass do you usually include the implicit construction of the superclass prior to the sub class constructor?
I usually wouldn't include it. The purpose of the UML sequence diagram is to show what happens between components. It shouldn't be read isolated from other parts of a design, so if a reader is unsure about what any of the components is (i.e. an instance of the subclass and the superclass), he or she should look into the - hopefully - accompanying class diagram.
sequence just shows the sequence of the logic of the module in question. Do you feel there is need to identify which method is truly being called? Also I would guess that the purpose of having a parent clas have a reference to a subclass is that until runtime you won't know which subclass is actually being referred to. If this is not the case, then should the concrete subclass be referred to explictly? does the method being called whether on the subclass or parent class alter the sequence in some way?