How can a class, in Python, inherit from 2 possible superclasses? - python

I'm currently working on platforms in a 2D game in Python. I created 1 superclass: Block. I also created 2 subclasses of Block: Solid (you can't jump through) & Semi_Solid (you can jump through from below). Now I would like to add a class Platform (to allow these blocks to move) that inherits from Solid or Semi_Solid, so its instances could have either the attributes of Solid or Semi_Solid.
So how can I create instances of Platform that can either inherit from Solid or Semi_Solid? Am I obliged to create 2 different classes ?
So I tried:
class Block:
pass
class Solid(Block):
pass
class Semi_Solid(Block):
pass
x = "solid"
class Platform(Solid if x=="solid" else Semi_Solid):
pass
obj1 = Platform()
x = "semi-solid"
obj2 = Platform()
But the change of x is not taken into account. I got 2 solid platforms
I made several others tests, but none of them was successful. Thank you for any help.

Inheritance is probably the most overrated OO feature, and alas usually presented as the one-size-fits-all solution in most introductory OO literature. The truth is that the real main OO features are encapsulation (which is not data hiding per se, but the ability to define self-contained componants that group together state and behaviour and abstract implementation details from client code) and polymorphic dispatch (the ability to use objects from different types / with different implementation in a uniform manner by the use of a common API).
At the semantic level, inheritance describes a "is a" relationship - if B inherits from A, then B is a A (cf the liskov substitution principle). So, is your "Platform" a "Solid" or is it a "SemiSolid" ? (hint: this is of course a rethoretical question).
At the implementation level, inheritance is, mostly, a fixed (static) and somehow restricted form of composition / delegation - whatever is not implemented in the child class is delegated to its parent(s). Good OO design is based on separating responsabilites and separate invariants from variants, delegating the "variant" part to another object. This is examplified by the Strategy pattern and its close cousin the State pattern.
Chances are that the answer to your question is mostly to use the Strategy pattern to handle the behavioral difference between solid and semisolid blocks - in which case you'd only have one single Block class responsible of everything that's common to all kind of blocks, and strategies for the "jump thru" behaviour (and other eventual behavioral differences between blocks). Then your Platform class - which doesn't necessarily have to be Block subclass (might or not be the right design depending on the context) - would take either a "jump through" strategie as argument (if you decide to make it a Block) or a Block instance (created with the appropriate strategie) if you decide to not make it a Block subclass.
This not only solves your current problem, but also allow to add new strategies etc without touching existing code, and avoids combinatorial explosion of classes.
NB: you may want to get yourself a copy of the GOF "design patterns", not that much for the patterns catalog itself (however interesting it is), but mostly for the first (long) introductory part of the book which is so far the very best available text on proper OO design.

Related

How to structure classes such that I can easily inherit from a "Persistor" class which pickles the inherting object?

I'm writing a new library and I want to persist some objects. I want to use a mixin or some sort of adapter so I don't have to implement a database right away. I'm using pickle right now to store objects.
Let's say I have a User class. I want to load a User from the folder if the pickle exists. I wrote a Persistor class which takes an object and writes it to a specified location. Do I make the User class inherit from the Persistor class? If so, when the User class is instantiated, how then do I replace the object with the loaded object if a pickle eists? Or do I create a UserPersistor class? I'm simply looking to abstract away the loading and saving of state from the User class.
class User(Persistor???):
"""
Central class to hold all user attributes and relationships.
"""
def __init__(
self,
first_name: str,
username: str,
date_of_birth: datetime.date
):
self.first_name = first_name
self.username = username
self.date_of_birth = date_of_birth
import pickle
import os
class Persistor:
"""
Class whose job is to save and load state until we need a database.
"""
def __init__(
self,
persistence_key
):
self.persistence_key = persistence_key
self.persistence_path = "data/" + persistence_key
#property
def save_exists(self):
return os.path.exists(self.persistence_path)
def save(self):
outfile = open(self.persistence_path, 'wb')
pickle.dump(self, outfile)
outfile.close()
def load(self):
if self.save_exists:
infile = open(self.persistence_path, 'rb')
db = pickle.load(infile)
infile.close()
return db
def delete(self):
if self.save_exists:
os.remove(self.persistence_path)
Simple answer (and it's nothing Python-specific FWIW, this is just plain OO design): semantically, inheritance denotes a "is a" relationship - so if B inherits from A, then B is a A too (cf the Liskov substitution principle too). So the real question is: would you consider that a User is a Persistor ?
Another common, sensible and widely accepted design principle is the single responsability principle, which states that each component should have a single, well-defined responsability. So ask yourself if you really want persistance implementation details to become part of your User class responsabilities...
As for a last couple OO design guidelines, which are repeated all over the (long) introduction of the GoF's "Design patterns" book (actually one of the best texts on OO design FWIW - the introduction I mean, even if the patterns catalog is of interest too): you should favor composition/delegation over inheritance (inheritance being, technically speakin, a restricted form of composition/delegation), and you should always program to an interface ("interface" in the Java term - in most languages this means an abstract base class), never to an implementation (a concrete class). By combining both, you get well decoupled code that's easy to test, maintain and evolve. For example, if you make your User class inherit from Persistor (which is a concrete class), you cannot easily switch to other Persistor implementation, while if you use composition/delegation and an abstract base class defining the only the Persistor API, you can (theoretically...) use any Persistor implementation your User class.
Now that's for the theory, and reality is that some abstractions tend to be kind of leaky - for example, to be persisted using the pickle protocol, your User class has to be pickleable, so this is not totally transparent, so take the above principles with a grain of salt - more as food for thought than golden rules, that is. As far as I'm concerned I would probably use composition/delegation as the safest choice here, and eventually reconsider the whole design during implementation progress, as implementation often hilights design flaws (if you can spot them at least).
EDIT
From what I recall, you don't need to use interfaces in Python due to multiple inheritance. Does that change the "is a" rule just for Python?
Actually, inheritance serves two purposes: subtyping (as explained above), but also code reuse - which is why the GoF describes inheritance as "a restricted form of composition/delegation" (in that the child class has a reference to it's parent(s) and automagically delegates parts of it's operations).
Subtyping is a very important part of OO, since it forms the basis for generic code and polymorphic dispatch - so a given piece of code can work just the same with a collection of objects that are from different concrete type (implementation), as long as they implement the same interface.
Semantically, an "interface" is a defined set of (public) features (methods, attributes, properties etc). Now how an interface is technically defined depends on the language.
Statically typed languages need a formal definition of the interfaces a class implements so it can perform compile-time checks and eventually optimizations. Note that I wrote "interfaceS" - a class can implement more than one single interface, and that's actually a rather common case.
For (static) languages that support multiple inheritance, the obvious solution is to use abstract base classes for interface definitions. Java doesn't support multiple concrete inheritance (that's a design choice) so it has a distinct construct named "interfaces" - but it's really another name for pure abstract base classes ("pure": only definitions, no implementation at all)
In dynamic languages, there's actually no (technical) need for formal interface definitions (since there's no formal typechecking), so "interfaces" are quite often informal - you'll often find in dynamic languages docs terms like "list-like", "file-like" etc (to denote objects that behaves like lists or files).
Now while this works well in practice (most of the times at least), there are still good things to be said about formal interface definitions, if only for documentation (and also for the cases where simple polymorphic dispatch is not enough and you have to inspect your objects to find out what you should do with them - think recursing over a structure of arbitrarly nested dicts and lists of various objects) - so Python also have abstract base classes, and they are actually recommended for any non-trivial project.
In all cases, the "is a" relationship still holds to a certain degree (even if the child class is not necessarily a proper subtype according to Liskov's definition) since a subclass does inherit it's parent(s) class(es) implied interface(s).
NB : Python also have "protocols", which are more formally defined sets of special methods a class can implement and that will give instances of this class some special behaviours (cf descriptors or iterators).
Can I have my User inherit from object and Persistor and that would be python's way of saying that it gets that functionality?
Well of course yes you can - there's no technical restriction on this, it's just a design question: should your User class also BE a Persistor, or would it be "better" (depending on the definition of "better") to have two clearly distinct classes - one for the domain model (User), and a technical one for persistance (UserPersistor for example).
If I delegate the persistence logic to the Persistor class, I still need to call that from my User class code
Not necessarily... If you decide that persistance is not the User's responsability, then you can just see things the other way round: it's the Persistor that calls on your User object -and in this case, you actually don't even need composition/delegation at all.
If you got yourself the GoF, I strongly suggest you take some time reading it before you go on with your design decisions, paying attention to the first part. Just a warning though : once you're done, avoid the tentation to use each and all of the patterns in your project, always ask yourself if it makes sense for the concrete problem at hand and whether the extra complication (if any) will ever be of any use for this particular part of your code ;-)

What, if any, are the differences between implementing one class as a child of another versus having the child employ an instance of the parent? [duplicate]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
There are two schools of thought on how to best extend, enhance, and reuse code in an object-oriented system:
Inheritance: extend the functionality of a class by creating a subclass. Override superclass members in the subclasses to provide new functionality. Make methods abstract/virtual to force subclasses to "fill-in-the-blanks" when the superclass wants a particular interface but is agnostic about its implementation.
Aggregation: create new functionality by taking other classes and combining them into a new class. Attach an common interface to this new class for interoperability with other code.
What are the benefits, costs, and consequences of each? Are there other alternatives?
I see this debate come up on a regular basis, but I don't think it's been asked on
Stack Overflow yet (though there is some related discussion). There's also a surprising lack of good Google results for it.
It's not a matter of which is the best, but of when to use what.
In the 'normal' cases a simple question is enough to find out if we need inheritance or aggregation.
If The new class is more or less as the original class. Use inheritance. The new class is now a subclass of the original class.
If the new class must have the original class. Use aggregation. The new class has now the original class as a member.
However, there is a big gray area. So we need several other tricks.
If we have used inheritance (or we plan to use it) but we only use part of the interface, or we are forced to override a lot of functionality to keep the correlation logical. Then we have a big nasty smell that indicates that we had to use aggregation.
If we have used aggregation (or we plan to use it) but we find out we need to copy almost all of the functionality. Then we have a smell that points in the direction of inheritance.
To cut it short. We should use aggregation if part of the interface is not used or has to be changed to avoid an illogical situation. We only need to use inheritance, if we need almost all of the functionality without major changes. And when in doubt, use Aggregation.
An other possibility for, the case that we have an class that needs part of the functionality of the original class, is to split the original class in a root class and a sub class. And let the new class inherit from the root class. But you should take care with this, not to create an illogical separation.
Lets add an example. We have a class 'Dog' with methods: 'Eat', 'Walk', 'Bark', 'Play'.
class Dog
Eat;
Walk;
Bark;
Play;
end;
We now need a class 'Cat', that needs 'Eat', 'Walk', 'Purr', and 'Play'. So first try to extend it from a Dog.
class Cat is Dog
Purr;
end;
Looks, alright, but wait. This cat can Bark (Cat lovers will kill me for that). And a barking cat violates the principles of the universe. So we need to override the Bark method so that it does nothing.
class Cat is Dog
Purr;
Bark = null;
end;
Ok, this works, but it smells bad. So lets try an aggregation:
class Cat
has Dog;
Eat = Dog.Eat;
Walk = Dog.Walk;
Play = Dog.Play;
Purr;
end;
Ok, this is nice. This cat does not bark anymore, not even silent. But still it has an internal dog that wants out. So lets try solution number three:
class Pet
Eat;
Walk;
Play;
end;
class Dog is Pet
Bark;
end;
class Cat is Pet
Purr;
end;
This is much cleaner. No internal dogs. And cats and dogs are at the same level. We can even introduce other pets to extend the model. Unless it is a fish, or something that does not walk. In that case we again need to refactor. But that is something for an other time.
At the beginning of GOF they state
Favor object composition over class inheritance.
This is further discussed here
The difference is typically expressed as the difference between "is a" and "has a". Inheritance, the "is a" relationship, is summed up nicely in the Liskov Substitution Principle. Aggregation, the "has a" relationship, is just that - it shows that the aggregating object has one of the aggregated objects.
Further distinctions exist as well - private inheritance in C++ indicates a "is implemented in terms of" relationship, which can also be modeled by the aggregation of (non-exposed) member objects as well.
Here's my most common argument:
In any object-oriented system, there are two parts to any class:
Its interface: the "public face" of the object. This is the set of capabilities it announces to the rest of the world. In a lot of languages, the set is well defined into a "class". Usually these are the method signatures of the object, though it varies a bit by language.
Its implementation: the "behind the scenes" work that the object does to satisfy its interface and provide functionality. This is typically the code and member data of the object.
One of the fundamental principles of OOP is that the implementation is encapsulated (ie:hidden) within the class; the only thing that outsiders should see is the interface.
When a subclass inherits from a subclass, it typically inherits both the implementation and the interface. This, in turn, means that you're forced to accept both as constraints on your class.
With aggregation, you get to choose either implementation or interface, or both -- but you're not forced into either. The functionality of an object is left up to the object itself. It can defer to other objects as it likes, but it's ultimately responsible for itself. In my experience, this leads to a more flexible system: one that's easier to modify.
So, whenever I'm developing object-oriented software, I almost always prefer aggregation over inheritance.
I gave an answer to "Is a" vs "Has a" : which one is better?.
Basically I agree with other folks: use inheritance only if your derived class truly is the type you're extending, not merely because it contains the same data. Remember that inheritance means the subclass gains the methods as well as the data.
Does it make sense for your derived class to have all the methods of the superclass? Or do you just quietly promise yourself that those methods should be ignored in the derived class? Or do you find yourself overriding methods from the superclass, making them no-ops so no one calls them inadvertently? Or giving hints to your API doc generation tool to omit the method from the doc?
Those are strong clues that aggregation is the better choice in that case.
I see a lot of "is-a vs. has-a; they're conceptually different" responses on this and the related questions.
The one thing I've found in my experience is that trying to determine whether a relationship is "is-a" or "has-a" is bound to fail. Even if you can correctly make that determination for the objects now, changing requirements mean that you'll probably be wrong at some point in the future.
Another thing I've found is that it's very hard to convert from inheritance to aggregation once there's a lot of code written around an inheritance hierarchy. Just switching from a superclass to an interface means changing nearly every subclass in the system.
And, as I mentioned elsewhere in this post, aggregation tends to be less flexible than inheritance.
So, you have a perfect storm of arguments against inheritance whenever you have to choose one or the other:
Your choice will likely be the wrong one at some point
Changing that choice is difficult once you've made it.
Inheritance tends to be a worse choice as it's more constraining.
Thus, I tend to choose aggregation -- even when there appears to be a strong is-a relationship.
The question is normally phrased as Composition vs. Inheritance, and it has been asked here before.
I wanted to make this a comment on the original question, but 300 characters bites [;<).
I think we need to be careful. First, there are more flavors than the two rather specific examples made in the question.
Also, I suggest that it is valuable not to confuse the objective with the instrument. One wants to make sure that the chosen technique or methodology supports achievement of the primary objective, but I don't thing out-of-context which-technique-is-best discussion is very useful. It does help to know the pitfalls of the different approaches along with their clear sweet spots.
For example, what are you out to accomplish, what do you have available to start with, and what are the constraints?
Are you creating a component framework, even a special purpose one? Are interfaces separable from implementations in the programming system or is it accomplished by a practice using a different sort of technology? Can you separate the inheritance structure of interfaces (if any) from the inheritance structure of classes that implement them? Is it important to hide the class structure of an implementation from the code that relies on the interfaces the implementation delivers? Are there multiple implementations to be usable at the same time or is the variation more over-time as a consequence of maintenance and enhancememt? This and more needs to be considered before you fixate on a tool or a methodology.
Finally, is it that important to lock distinctions in the abstraction and how you think of it (as in is-a versus has-a) to different features of the OO technology? Perhaps so, if it keeps the conceptual structure consistent and manageable for you and others. But it is wise not to be enslaved by that and the contortions you might end up making. Maybe it is best to stand back a level and not be so rigid (but leave good narration so others can tell what's up). [I look for what makes a particular portion of a program explainable, but some times I go for elegance when there is a bigger win. Not always the best idea.]
I'm an interface purist, and I am drawn to the kinds of problems and approaches where interface purism is appropriate, whether building a Java framework or organizing some COM implementations. That doesn't make it appropriate for everything, not even close to everything, even though I swear by it. (I have a couple of projects that appear to provide serious counter-examples against interface purism, so it will be interesting to see how I manage to cope.)
I'll cover the where-these-might-apply part. Here's an example of both, in a game scenario. Suppose, there's a game which has different types of soldiers. Each soldier can have a knapsack which can hold different things.
Inheritance here?
There's a marine, green beret & a sniper. These are types of soldiers. So, there's a base class Soldier with Marine, Green Beret & Sniper as derived classes
Aggregation here?
The knapsack can contain grenades, guns (different types), knife, medikit, etc. A soldier can be equipped with any of these at any given point in time, plus he can also have a bulletproof vest which acts as armor when attacked and his injury decreases to a certain percentage. The soldier class contains an object of bulletproof vest class and the knapsack class which contains references to these items.
I think it's not an either/or debate. It's just that:
is-a (inheritance) relationships occur less often than has-a (composition) relationships.
Inheritance is harder to get right, even when it's appropriate to use it, so due diligence has to be taken because it can break encapsulation, encourage tight coupling by exposing implementation and so forth.
Both have their place, but inheritance is riskier.
Although of course it wouldn't make sense to have a class Shape 'having-a' Point and a Square classes. Here inheritance is due.
People tend to think about inheritance first when trying to design something extensible, that is what's wrong.
Favour happens when both candidate qualifies. A and B are options and you favour A. The reason is that composition offers more extension/flexiblity possiblities than generalization. This extension/flexiblity refers mostly to runtime/dynamic flexibility.
The benefit is not immediately visible. To see the benefit you need to wait for the next unexpected change request. So in most cases those sticked to generlalization fails when compared to those who embraced composition(except one obvious case mentioned later). Hence the rule. From a learning point of view if you can implement a dependency injection successfully then you should know which one to favour and when. The rule helps you in making a decision as well; if you are not sure then select composition.
Summary: Composition :The coupling is reduced by just having some smaller things you plug into something bigger, and the bigger object just calls the smaller object back. Generlization: From an API point of view defining that a method can be overridden is a stronger commitment than defining that a method can be called. (very few occassions when Generalization wins). And never forget that with composition you are using inheritance too, from a interface instead of a big class
Both approaches are used to solve different problems. You don't always need to aggregate over two or more classes when inheriting from one class.
Sometimes you do have to aggregate a single class because that class is sealed or has otherwise non-virtual members you need to intercept so you create a proxy layer that obviously isn't valid in terms of inheritance but so long as the class you are proxying has an interface you can subscribe to this can work out fairly well.

Difference between Encapsulation and Abstraction

I had an interview today. I had a question from OOP, about the difference between Encapsulation & Abstraction?
I replied to my knowledge that Encapsulation is basically binding data members & member functions into a single unit called Class. Whereas Abstraction is basically to hide implementation complexity & provide ease of access to the users. I thought she would be okay with my answer. But she queried if the purpose of both is to hide information then what the actual difference between these two is? I could not give any answer to her.
Before asking this question, I read other threads on StackOverFlow about the difference between these two OOPs concepts. But I am not finding myself in a position to convince the interviewer.
Can anyone please justify it with the simplest example?
Encapsulation hides variables or some implementation that may be changed so often in a class to prevent outsiders access it directly. They must access it via getter and setter methods.
Abstraction is used to hide something too, but in a higher degree (class, interface). Clients who use an abstract class (or interface) do not care about what it was, they just need to know what it can do.
This image sums pretty well the difference between both:
Source here
Encapsulation: Wrapping code and data together into a single unit. Class is an example of encapsulation, because it wraps the method and property.
Abstraction: Hiding internal details and showing functionality only. Abstraction focus on what the object does instead of how it does. It provides generalized view of classes.
int number = 5;
string aStringNumber = number.ToString();
Here, ToString() is abstraction. And how this mechanism number variable converted to string and initialize into aStringNumber is encapsulation.
Let us take a real world example of calculator. Encapsulation is the internal circuits, battery, etc., that combine to make it a calculator. Abstraction is the different buttons like on-off, clear and other buttons provided to operate it.
Abstraction - is the process (and result of this process) of identifying the common essential characteristics for a set of objects.
One might say that Abstraction is the process of generalization: all objects under consideration are included in a superset of objects, all of which possess given properties (but are different in other respects).
Encapsulation - is the process of enclosing data and functions manipulating this data into a single unit, so that to hide the internal implementation from the outside world.
This is a general answer not related to a specific programming language (as was the question). So the answer is: abstraction and encapsulation have nothing in common. But their implementations might relate to each other (say, in Java: Encapsulation - details are hidden in a class, Abstraction - details are not present at all in a class or interface).
Yes !!!!
If I say Encapsulation is a kind of an advanced specific scope abstraction,
How many of you read/upvote my answer. Let's dig into why I am saying this.
I need to clear two things before my claim.
One is data hiding and, another one is the abstraction
Data hiding
Most of the time, we will not give direct access to our internal data. Our internal data should not go out directly that is an outside person can't access our internal data directly. It's all about security since we need to protect the internal states of a particular object.
Abstraction
For simplicity, hide the internal implementations is called abstraction. In abstraction, we only focus on the necessary things. Basically, We talk about "What to do" and not "How to do" in abstraction.
Security also can be achieved by abstraction since we are not going to highlight "how we are implementing". Maintainability will be increased since we can alter the implementation but it will not affect our end user.
I said, "Encapsulation is a kind of an advanced specific scope abstraction". Why? because we can see encapsulation as data hiding + abstraction
encapsulation = data hiding + abstraction
In encapsulation, we need to hide the data so the outside person can not see the data and we need to provide methods that can be used to access the data. These methods may have validations or other features inside those things also hidden to an outside person. So here, we are hiding the implementation of access methods and it is called abstraction.
This is why I said like above encapsulation is a kind of abstraction.
So Where is the difference?
The difference is the abstraction is a general one if we are hiding something from the user for simplicity, maintainability and security and,
encapsulation is a specific one for which is related to internal states security where we are hiding the internal state (data hiding) and we are providing methods to access the data and those methods implementation also hidden from the outside person(abstraction).
Why we need abstraction
When you do designs, you will not talk about implementations. You say If you give these parameters to this method it will give these output.
We hide the internal implementation of the method and talk about what it will do so this is an abstraction.
Example
public int add(int a, int b);
This method definition tells us that if you give two variables it will do addition and return the result.
here we will not look at the implementation and we ay only what this method does and not how it does.
Method implementations can be differs based on developers.
1.
public int add(int a, int b){
return a + b;
}
public int add(int a, int b){
return b + a;
}
Two methods are doing the same thing what their implementation differs.
Basically,
Abstraction is needed to model the system. Encapsulation is needed to enhance system security.
Abstraction:
Is usually done to provide polymorphic access to a set of classes.
An abstract class cannot be instantiated thus another class will have to derive from it to create a more concrete representation.
A common usage example of an abstract class can be an implementation of a template method design pattern where an abstract injection point is introduces so that the concrete class can implement it in its own "concrete" way.
see: http://en.wikipedia.org/wiki/Abstraction_(computer_science)
Encapsulation:
It is the process of hiding the implementation complexity of a specific class from the client that is going to use it, keep in mind that the "client" may be a program or event the person who wrote the class.
see: http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)
There is a great article that touches on differences between Abstraction, Encapsulation and Information hiding in depth: http://www.tonymarston.co.uk/php-mysql/abstraction.txt
Here is the conclusion from the article:
Abstraction, information hiding, and encapsulation are very different,
but highly-related, concepts. One could argue that abstraction is a
technique that helps us identify which specific information should be
visible, and which information should be hidden. Encapsulation is then
the technique for packaging the information in such a way as to hide
what should be hidden, and make visible what is intended to be
visible.
A very practical example is.
let's just say I want to encrypt my password.
I don't want to know the details, I just call
encryptionImpl.encrypt(password) and it returns an encrypted
password.
public interface Encryption{ public String encrypt(String password); }
This is called abstraction. It just shows what should be done.
Now let us assume We have Two types of Encryption Md5 and RSA which
implement Encryption from a third-party encryption jar.
Then those Encryption classes have their own way of implementing
encryption which protects their implementation from outsiders
This is called Encapsulation. Hides how it should be done.
Remember:what should be done vs how it should be done.
Hiding complications vs Protecting implementations
Yes, it is true that Abstraction and Encapsulation are about hiding.
Using only relevant details and hiding unnecessary data at Design Level is called Abstraction. (Like selecting only relevant properties for a class 'Car' to make it more abstract or general.)
Encapsulation is the hiding of data at Implementation Level. Like how to actually hide data from direct/external access. This is done by binding data and methods to a single entity/unit to prevent external access. Thus, encapsulation is also known as data hiding at implementation level.
Encapsulation:
Hiding something, sort of like medicine capsule. We don't know what is in the capsule, we just take it. Same as in programming - we just hide some special code of method or property and it only gives output, same as capsule. In short, encapsulation hides data.
Abstraction:
Abstraction means hiding logic or implementation. For example, we take tablets and see their color and but don't know what is the purpose of this and how it works with the body.
difference in both is just the View Point
Encapsulation word is used for hiding data if our aim is to prevent client seeing inside view of our logic
Abstraction word is used for hiding data if our aim is to show our client a out side view
Outside view means that let suppose
BubbleSort(){
//code
swap(x,y);
}
here we use swap in bubble sort for just showing our client what logic we are applying, If we replace swap(x,y) with whole code here, In a single instance he/she can't understand our logic
Let me explain it in with the same example discussed above. Kindly consider the same TV.
Encapsulation: The adjustments we can make with the remote is a good example - Volume UP/DOWN, Color & Contrast - All we can do is adjust it to the min and max value provided and cannot do anything beyond what is provided in the remote - Imagine the getter and setter here(The setter function will check whether the value provided is valid if Yes, it process the operation if not won't allow us to make changes - like we cannot decrease the volume beyond zero even we press the volume down button a hundred times).
Abstraction: We can take the same example here but with a higher Degree/Context. The volume down button will decrease the volume - and this is the info we provide to the user and the user is not aware of neither the infrared transmitter inside the remote nor the receiver in the TV and the subsequent process of parsing the signal and the microprocessor architecture inside the TV. Simply put it is not needed in the context - Just provide what is necessary. One can easily relate the Text book definition here ie., Hiding the inner implementation and only providing what it will do rather than how it do that!
Hope it clarifies a bit!
Briefly, Abstraction happens at class level by hiding implementation and implementing an interface to be able to interact with the instance of the class. Whereas, Encapsulation is used to hide information; for instance, making the member variables private to ban the direct access and providing getters and setters for them for indicrect access.
Encapsulation is wrapping up of data and methods in a single unit and making the data accessible only through methods(getter/setter) to ensure safety of data.
Abstraction is hiding internal implementation details of how work is done.
Take and example of following stack class:
Class Stack
{
private top;
void push();
int pop();
}
Now encapsulation helps to safeguard internal data as top cannot be accessed directly outside.
And abstraction helps to do push or pop on stack without worrying about what are steps to push or pop
Abstraction
As the name suggests abstract means summary or brief about somtehing. In case of OOP Abstract Classes are the ones which do not contain every information about that object in real world, for eg. you want to book a hotel room, if your object is that room you mainly care about:
its prices, size, beds etc.
but you do not care about
the wiring they have used in the hotel room for electricity.
which cement they have used to build it up
So, you get abstracted information about the room which you care about.
On the other hand, Encapsulation is basically capsulating the related information together, for eg. you booked the hotel room, you go there and switch on a bulb by pressing the switch. Now the switch object has all internal wirings which are required to switch that bulb ON, but you really do not care about those wirings. You care only about bulb is switched ON or not.
Now one can argue that abstraction also applies here:
one can say the internal wiring of the switch is also abstracted to you, so this must be case of abstraction but here are some subtle differences:
Abstraction is more of a contextual thing, it does not have the non abstracted information, like the wiring info which you do not care about, is not present in the context of website for booking hotel room (like your class room do not have information about the wiring grid of it, since this room is delegated for online booking only) , whereas encapsulation is more granular, it means hiding and capsulating the granular things which you do not need to care about, for switching the bulb ON the switch hides the wiring inside the switch board (like private attributes/methods of classes).
Now the switch class has the information but it is hidden to you. On the other hand room class does not have the information about wiring design of a hotel room since it is not even in the context of online booking of the room
Thus, the abstraction is more related to classes and encapsulation is more related to internal of the class objects, attributes and methods.
Abstraction
is the process of hiding the how, and only showing the what
the purpose is to simplify information and hide unnecessary details from the user
Encapsulation
is the process of wrapping data and functionality into a single unit
the purpose is to protect data, by preventing direct access and only providing a safer and indirect way
In simple terms, Encapsulation is data hiding(information hiding) while Abstraction is detail hiding(implementation hiding)
Abstraction
In Java, abstraction means hiding the information to the real world. It establishes the contract between the party to tell about “what should we do to make use of the service”.
Example, In API development, only abstracted information of the service has been revealed to the world rather the actual implementation. Interface in java can help achieve this concept very well.
Interface provides contract between the parties, example, producer and consumer. Producer produces the goods without letting know the consumer how the product is being made. But, through interface, Producer let all consumer know what product can buy. With the help of abstraction, producer can markets the product to their consumers.
Encapsulation:
Encapsulation is one level down of abstraction. Same product company try shielding information from each other production group. Example, if a company produce wine and chocolate, encapsulation helps shielding information how each product Is being made from each other.
If I have individual package one for wine and another one for chocolate, and if all the classes are declared in the package as default access modifier, we are giving package level encapsulation for all classes.
Within a package, if we declare each class filed (member field) as
private and having a public method to access those fields, this way
giving class level encapsulation to those fields
If I am the one who faced the interview, I would say that as the end-user perspective abstraction and encapsulation are fairly same. It is nothing but information hiding. As a Software Developer perspective, Abstraction solves the problems at the design level and Encapsulation solves the problem in implementation level
Encapsulation is the composition of meaning.
Abstraction is the simplification of meaning.
Just a few more points to make thing clear,
One must not confuse data abstraction and the abstract class. They are different.
Generally we say abstract class or method is to basically hide something. But no.. That is wrong. What is the word abstract means ? Google search says the English word abstraction means
"Existing in thought or as an idea but not having a physical or concrete existence."
And thats right in case of abstract class too. It is not hiding the content of the method but the method's content is already empty (not having a physical or concrete existence) but it determines how a method should be (existing in thought or as an idea) or a method should be in the calss.
So when do you actually use abstract methods ?
When a method from base class will differ in each child class that extends it.
And so you want to make sure the child class have this function implemented.
This also ensures that method, to have compulsory signature like, it must have n number of parameters.
So about abstract class!
- An Abstract class cannot be instantiated only extended! But why ?
A class with abstract method must be prevented from creating its own instance because the abstract methods in it, are not having any meaningful implementation.
You can even make a class abstract, if for some reason you find that it is meaning less to have a instance of your that class.
An Abstract class help us avoid creating new instance of it!
An abstract method in a class forces the child class to implement that function for sure with the provided signature!
Abstraction: what are the minimum functions and variables that should be exposed to the outside of our class.
Encapsulation: how to achieve this requirement, meaning how to implement it.

Basic usage of python class inheritance

I'm just getting started with Python, and am trying to figure out the Right Way to use classes.
My program currently has two classes, call them Planner and Model. The Planner is model-agnostic, given that any Model it uses presents a consistent interface. So, it seems like if I want to have several different available models, they should all inherit from something, in order to enforce the consistent interface. Additionally, some of the Model classes will share functionality. For example, a singleAgent Model might simulate one agent, while a doubleAgent Model would simulate two agents, each behaving just like the singleAgent.
So - how should I implement this / what language features do I need?
EDIT: Thanks for the fast responses straightening me out about duck classes! So, it sounds like I would only use inheritance if I wanted to override a subset of another Model's functionality? (And for my doubleAgent, I'd probably just use singleAgents as class members?)
I've taken a look through a few other questions with similar tags, but they seem to be more concerned with syntax rather than design choices. I've also looked at the official Python documentation on classes and not found what I'm looking for. (Possibly because I don't know enough to recognize it.)
In Python you don't generally use quite the same approaches to OOP as in statically typed languages. Specifically you don't actually need an object to implement a specific interface or derive from an abstract base class and so on. Rather that object just needs to be able to do the required operations. This is colloquially known as duck typing. If it walks like a duck and talks like a duck then, to all intents and purposes it is a duck.
So just decide what methods are required for your objects and make sure that they always have them. Should you wish to share implementation between different actors in your system then you can consider class inheritance. But if not then you may as well implement disjoint class hierarchies.
One of Python's strengths (and, as many would argue, weaknesses) is that it does not rely on compile-time type checking to enforce interfaces. This means that it is not required for a set of objects to inherit from a common base class in order to have the same interface - they can still be used interchangeably in any function. This behavior is commonly known as duck typing.
In fact, because Python is dynamically typed, you would be hard pressed to "enforce a consistent interface", as you said. For this reason, things like zope.interface have been created. The main benefit you'll get from classes in your case is code reuse - if all Model types implement some common behavior.
To take this even one step further, if you should have some unrelated object type in a third party library out of your control that you wish to use as a Model, you can even do what is called "monkey patching" or "duck punching" in order to add the code necessary to provide your Model interface!
Basically the link you provided on Classes in Python answers all your questions under the section about inheritance.
In your case just define a class called Model and then two subclasses: singleAgent und doubleAgent.:
class Model:
pass
class singleAgent(Model):
pass
If you really, really need abstract classes take a look into "abstract base class"es: http://docs.python.org/library/abc.html

In Ruby or Python can the very concept of Class be rewritten?

first time at stack overflow.
I'm looking into using some of the metaprogramming features provided by Ruby or Python, but first I need to know the extent to which they will allow me to extend the language. The main thing I need to be able to do is to rewrite the concept of Class. This doesn't mean that I want to rewrite a specific class during run time, but rather I want to make my own conceptualization of what a Class is. To be a smidge more specific here, I want to make something that is like what people normally call a Class, but I want to follow an "open world" assumption. In the "closed world" of normal Classes, if I declare Poodle to be a subclass of Dog to be a subclass of Animal, then I know that Poodle is not going to also be a type of FurCoat. However, in an open world Class, then the Poodle object I've defined may or may not be and object of type FurCoat and we won't know for sure until I explain that I can wear the poodle. (Poor poodle.) This all has to do with a study I'm doing concerning OWL ontologies.
Just so you know, I've tried to find information online, but due to the overloading of terms here I haven't found anything helpful.
Super thanks,
John
UPDATE: I just thought of a good use case for my open-world concept of Class. Perhaps this will provide a better understanding of what I really wish to do. I want to be able to "describe" a Class rather than define it. For instance, I want to be able to say that a Dog is anything that a) has four legs b) barks. Then I want to be able to create an object of unspecified Class, and describe that this object has four legs. At this point the object is still of unspecified type. Then I want to say that the object barks. At this point, the object will be known to be (possibly among other things) a Dog.
Sounds like duck typing to me. Just declare the methods you want and remember that it's easier to ask forgiveness than permission:
try:
poodle.wear()
except (AttributeError, TypeError):
pass
I agree with Samir that it just sounds like duck typing. You don't need to care what 'type' an object really 'is' you only need bother with what an object can 'do'. This is true in both Ruby and Python.
However if you really are checking the types of classes and you really do need to have a Poodle object optionally also be a FurCoat at runtime, then the way to do this in Ruby is to mixin a FurCoat module into the Poodle object, as follows:
class Poodle; end
module FurCoat; def wear; end; end
my_poodle = Poodle.new
my_poodle.is_a?(Poodle) #=> true
my_poodle.is_a?(FurCoat) #=> false
my_poodle.wear #=> NoMethodError
# now we mix in the FurCoat module
my_poodle.extend(FurCoat)
# my_poodle is now also a FurCoat
my_poodle.is_a?(Poodle) #=> true (still)
my_poodle.is_a?(FurCoat) #=> true
my_poodle.wear #=> the wear method now works
EDIT (due to your updated question):
You still do not need to rewrite Class to achieve what you want, you just need to monkey-patch the kind_of? and is_a? (and potentially instance_of?) methods on Ruby's Kernel module. Since Ruby has open classes this is easily done:
class Module
def obj_implements_interface?(obj)
false
end
end
module Kernel
alias_method :orig_is_a?, :is_a?
def is_a?(klass)
orig_is_a?(klass) || klass.obj_implements_interface?(self)
end
end
And then define for each class (or module) what it means for an object to implement its interface:
class Dog
def self.obj_implements_interface?(obj)
obj.respond_to?(:bark) && obj.respond_to?(:num_legs) && obj.num_legs == 4
end
end
module FurCoat
def self.obj_implements_interface?(obj)
obj.respond_to?(:wear)
end
end
Now test it:
my_poodle = Poodle.new
my_poodle.is_a?(FurCoat) #=> false
# now define a wear method on my_poodle
def my_poodle.wear; end
my_poodle.is_a?(FurCoat) #=> true
No, you cannot do that in Ruby. In Ruby, the object model is baked into the language specification and is not accessible (and certainly not modifiable) from within the program. Even in Rubinius, which is a Ruby implementation written mostly in Ruby, and with amazing metaprogramming capabilities that extend far beyond what the Ruby specification offers, some of the fundamental primitives are hardwired in C++.
I am not that intimately familiar with Python, but I'm pretty sure it's the same way, even in PyPy.
You might be able to do that in Smalltalk, by modifying (or subclassing) the Behavior class, which is the superclass of Class and defines the behavior of both classes and metaclasses.
You can certainly do that in CLOS, or more precisely using CLOS's MOP (Meta-Object Protocol). After all, that's what a MOP is for: defining the object model.
The closest OO concept to what you are describing seems to be that of Predicate Classes. A predicate class is a class whose instances are not defined statically, but by a set of predicates: all objects that satisfy the set of predicates are instances of the class, as soon as and for as long as the predicate holds. In a language with mutable state, this obviously means that objects can "move" in and out of predicate classes as their state changes. It also means that at any given time an object can be an instance of many or no predicate classes.
The only mainstream language (for a rather broad definition of "mainstream") I know of that has predicate classes is Factor.
However, please note that even here, the predicates are defined and an object either fulfils them or it doesn't. There is no concept of discovering whether or not an object fulfils a predicate at runtime.
You might also be interested in Clojure's idea of ad-hoc taxonomy.
Last, but certainly not least, you might take a look at Mikel Evins's object system called Categories. The best description of Categories, is to simply follow the blog entries in chronological order:
Protocols
Categories
A peek at Categories
No Kings in Rome
Up pops a reasonable facsimile thereof
Different Categories of Categories
Categories Bugs
Flat Cat in a C3 Vat
Categories 0.2
Bard
Bard intricacies
In the future, most of the development on Categories is going to be done in Mikel's new language Bard and you can follow their progress by following the Categories tag and the Bard tag on Mikel's new blog.
However, in general, I would say that the fact that Knowledge Management and Object-Orientation both use the word class is mainly a historic accident. I don't think that modeling one with the other is a good fit.
In Python you can change the inheritence of a class at runtime, but at every given time a class is not a subclass of another one unless declared otherwise. There is no "may or may not" - that would need ternary logic which Python doesn't support. But of course you can write your own "Is-a" and "Has-a" functions to map OWL ontologies to Python classes.
I think relying on a class structure, no matter how dynamic, is a step backwards when representing information with an open word assumption.
Classes serving as templates and objects serving as instances give absolutely no advantage when used with an OWA. Consider a Person class where we encode the knowledge that a person has 2 legs. However, we cannot deduce that a instance of Person will have two legs, as the person may have a disability.
If class properties don't mean anything as in the above example, there seems little point in using them or any other hierarchical structure to encode information.

Categories