473,769 Members | 2,143 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Difference between type and class

Hello,

Can someone explain to me the difference between a type and a class?
After reading http://www.cafepy.com/article/python_types_and_objects/
it seems to me that classes and types are actually the same thing:

- both are instances of a metaclass, and the same metaclass ('type')
can instantiate both classes and types.
- both can be instantiated and yield an "ordinary" object
- I can even inherit from a type and get a class

So why does Python distinguish between e.g. the type 'int' and the
class 'myclass'? Why can't I say that 'int' is a class and 'myclass'
is a type?

I hope I have managed to get across the point of my confusion...
Thanks in advance,

-Nikolaus

--
»It is not worth an intelligent man's time to be in the majority.
By definition, there are already enough people to do that.«
-J.H. Hardy

PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C
Jul 31 '08
21 5201
Maric Michaud <ma***@aristote .infowrites:
Le Thursday 31 July 2008 16:46:28 Nikolaus Rath, vous avez écritÂ*:
>Maric Michaud <ma***@aristote .infowrites:
Can someone explain to me the difference between a type and a class?

If your confusion is of a more general nature I suggest reading the
introduction of `Design Patterns' (ISBN-10: 0201633612), under
`Specifying Object Interfaces'.

In short: A type denotes a certain interface, i.e. a set of signatures,
whereas a class tells us how an object is implemented (like a
blueprint). A class can have many types if it implements all their
interfaces, and different classes can have the same type if they share a
common interface. The following example should clarify matters:

Of course, this is what a type means in certain literature about OO
(java-ish), but this absolutely not what type means in Python. Types
are a family of object with a certain status, and they're type is
"type", conventionnaly named a metatype in standard OO.

[...]

Hmm. Now you have said a lot about Python objects and their type, but
you still haven't said what a type actually is (in Python) and in what
way it is different from a class. Or did I miss something?

This paragraph ?

"""
- types, or classes, are all instance of type 'type' (or a subclass of it),
Well, I couldn't quite make sense of '..are instance of type...'
without knowing what you actually meant with "type* in this context,
but...
Maybe it's still unclear that "types" and "classes" *are* synonyms
in Python.
...in this case it becomes clear. Then my question reduces to the one
in the other post (why do 'int' and 'myint' have different __repr__
results).
Already thanks for your help,
-Nikolaus

--
»It is not worth an intelligent man's time to be in the majority.
By definition, there are already enough people to do that.«
-J.H. Hardy

PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C
Jul 31 '08 #11
Le Thursday 31 July 2008 17:00:51 Nikolaus Rath, vous avez écritÂ*:
There are some confusion about the terms here.

Classes are instances of type 'type',

Could you please clarify what you mean with 'instance of type X'? I
guess you mean that 'y is an instance of type X' iif y is constructed
by instantiating X. Is that correct?
Correct, you can verify this with the isinstance builtin :
>>>[1]: isinstance(int( ), int)
...[1]: True
>>>[2]: isinstance(int, object)
...[2]: True
>>>[3]: isinstance(int, type)
...[3]: True
>>>[4]: class A(object) : pass
...:
>>>[5]: isinstance(A, type)
...[5]: True
What the <type intmeans is that int is not a user type but a
builtin type, instances of int are not types (or classes) but common
objects, so its nature is the same as any classes.

The way it prints doesn't matter, it's just the __repr__ of any instance,
and the default behavior for instances of type is to return '<class XX>',
but it can be easily customized.

But 'int' is an instance of 'type' (the metaclass):
>int.__class_ _

<type 'type'>

so it should also return '<class int>' if that's the default behavior
of the 'type' metaclass.
The fact that a class is an instance of type, which it is always true, doesn't
mean its metaclass is "type", it could be any subclass of type :
>>>[6]: class A(object) :
...: class __metaclass__(t ype) :
...: def __repr__(self) : return "<type A>"
...:
...:
>>>[7]: isinstance(A, type)
...[7]: True
>>>[8]: A.__class__
...[8]: <class '__main__.__met aclass__'>
>>>[9]: issubclass(A.__ class__, type)
...[9]: True

I think that to get '<type int>' one would have to define a new
metaclass like this:

def type_meta(type) :
Â* Â* def __repr__(self)
Â* Â* Â* Â* Â*return "<type %s>" % self.__name__

and then one should have int.__class__ == type_meta. But obviously
that's not the case. Why?

Moreover:
>class myint(int):

... Â* Â*pass
...
>myint.__class_ _ == int.__class__

True
*is* comparaison fits better here.
>int

<type 'int'>
>myint

<class '__main__.myint '>

despite int and myint having the same metaclass. So if the
representation is really defined in the 'type' metaclass, then
type.__repr__ has to make some kind of distinction between int and
myint, so they cannot be on absolute equal footing.
You're right, type(int) is type, the way it renders differently is a detailof
its implementation, you can do things with builtin types (written in C) you
coudn't do in pure python, exactly as you couldn't write recursive types
like 'object' and 'type'.
--
_____________

Maric Michaud
Jul 31 '08 #12
Maric Michaud <ma***@aristote .infowrites:
>>What the <type intmeans is that int is not a user type but a
builtin type, instances of int are not types (or classes) but common
objects, so its nature is the same as any classes.

The way it prints doesn't matter, it's just the __repr__ of any instance,
and the default behavior for instances of type is to return '<class XX>',
but it can be easily customized.

But 'int' is an instance of 'type' (the metaclass):
>>int.__class __

<type 'type'>

so it should also return '<class int>' if that's the default behavior
of the 'type' metaclass.

The fact that a class is an instance of type, which it is always true, doesn't
mean its metaclass is "type", it could be any subclass of type :
Yes, that is true. But it's not what I said above (and below).
'obj.__class__' gives the class of 'obj', so if 'int.__class__ is
type' then 'type' is the class of 'int' and 'int' is *not* an instance
of some metaclass derived from 'type'.
>I think that to get '<type int>' one would have to define a new
metaclass like this:

def type_meta(type) :
Â* Â* def __repr__(self)
Â* Â* Â* Â* Â*return "<type %s>" % self.__name__

and then one should have int.__class__ is type_meta. But obviously
that's not the case. Why?

Moreover:
>>class myint(int):

... Â* Â*pass
...
>>myint.__class __ is int.__class__
True
>>int
<type 'int'>
>>myint
<class '__main__.myint '>

despite int and myint having the same metaclass. So if the
representati on is really defined in the 'type' metaclass, then
type.__repr_ _ has to make some kind of distinction between int and
myint, so they cannot be on absolute equal footing.

You're right, type(int) is type, the way it renders differently is a
detail of its implementation, you can do things with builtin types
(written in C) you coudn't do in pure python, exactly as you
couldn't write recursive types like 'object' and 'type'.

If it is just a matter of different rendering, what's the reason for
doing it like that? Wouldn't it be more consistent and straightforward
to denote builtin types as classes as well?

And where exactly is this different rendering implemented? Could I
write my own type (in C, of course) and make it behave like e.g.
'int'? I.e. its rendering should be different and not inherited to
subclasses:

>>my_type
<strange_thin g 'my_type'>
>>a = my_type(42)
a.__class__
<strange_thin g 'my_type'>
>>class derived(my_type ):
pass
<class 'derived>

or would I have to change the implemention of 'type' for this (since
it contains the __repr__ function that renders the type)?
This is of course purely theoretical and probably without any
practical relevance. I'm if I just can't stop drilling, but I think
this is really interesting.
Best,
-Nikolaus

--
»It is not worth an intelligent man's time to be in the majority.
By definition, there are already enough people to do that.«
-J.H. Hardy

PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C
Jul 31 '08 #13
On Thu, 31 Jul 2008 13:32:39 +0200, Thomas Troeger wrote:
>Can someone explain to me the difference between a type and a class?

If your confusion is of a more general nature I suggest reading the
introduction of `Design Patterns' (ISBN-10: 0201633612), under
`Specifying Object Interfaces'.

In short: A type denotes a certain interface, i.e. a set of signatures,
whereas a class tells us how an object is implemented (like a
blueprint). A class can have many types if it implements all their
interfaces, and different classes can have the same type if they share a
common interface.
I fear you're introducing a rather complicated answer for a simple
question. In Python, the simple answer is that built-in objects like int,
float, str etc. are referred to as "types", and custom objects created
using the class keyword are referred to as "classes". This is a
historical distinction that will disappear in time.

We can see that types and classes already have the same type in Python:
>>class Parrot(object):
.... pass
....
>>type(Parrot )
<type 'type'>
>>type(str)
<type 'type'>
The following example should clarify matters:

class A:
def bar(self):
print "A"

Alas, you've chosen the worst-possible example to "clarify" matters,
because old-style classic classes are *not* unified with types, and will
disappear in the future:
>>class Old: # don't inherit from object
.... pass
....
>>type(Old)
<type 'classobj'>
So, to the Original Poster:

In Python, new-style classes and types are the same, but it is
traditional to refer to customer objects as "class" and built-in objects
as "types". Old-style classes are different, but you are discouraged from
using old-style classes unless you have a specific reason for needing
them (e.g. backwards compatibility).
--
Steven
Jul 31 '08 #14
On Thu, Jul 31, 2008 at 1:59 PM, Nikolaus Rath wrote:
If it is just a matter of different rendering, what's the reason for
doing it like that? Wouldn't it be more consistent and straightforward
to denote builtin types as classes as well?
Yes, and in Python 3, it will be so:
>>class myint(int): pass
....
>>int
<class 'int'>
>>myint
<class '__main__.myint '>

The reason the distinction is made currently is that before Python
2.2, "types" were built-in (or C extension) classes, and "classes"
were Python classes; it was not possible to subclass built-in types.
That "classic" style of classes are still supported in Python 2.2 and
above (but not in Python 3), by not inheriting from object or any
other built-in. However, for new-style classes, the only distinction
is in the repr.
>>class classic: pass
....
>>class newstyle(object ): pass
....
>>type(classi c)
<type 'classobj'>
>>type(classic( ))
<type 'instance'>
>>classic.__cla ss__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: class classic has no attribute '__class__'
>>classic().__c lass__
<class __main__.classi c at 0x64e70>
>>>
type(newstyle )
<type 'type'>
>>type(newstyle ())
<class '__main__.newst yle'>

Further reading:

http://www.python.org/download/relea....3/descrintro/
http://svn.python.org/view?rev=23331&view=rev
http://bugs.python.org/issue2565

-Miles
Jul 31 '08 #15
Miles <se*********@gm ail.comwrites:
On Thu, Jul 31, 2008 at 1:59 PM, Nikolaus Rath wrote:
>If it is just a matter of different rendering, what's the reason for
doing it like that? Wouldn't it be more consistent and straightforward
to denote builtin types as classes as well?

Yes, and in Python 3, it will be so:
[..]
http://svn.python.org/view?rev=23331&view=rev
That makes matters absolutely clear. Thanks a lot. No more questions
from my side ;-).
Best,

-Nikolaus
--
»It is not worth an intelligent man's time to be in the majority.
By definition, there are already enough people to do that.«
-J.H. Hardy

PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C
Aug 1 '08 #16
Steven D'Aprano <st***@REMOVE-THIS-cybersource.com .auwrites:
So, to the Original Poster:

In Python, new-style classes and types are the same, but it is
traditional to refer to customer objects as "class" and built-in
objects as "types". Old-style classes are different, but you are
discouraged from using old-style classes unless you have a specific
reason for needing them (e.g. backwards compatibility).
I see. Thanks a lot for the explanation.
Best,

-Nikolaus

--
»It is not worth an intelligent man's time to be in the majority.
By definition, there are already enough people to do that.«
-J.H. Hardy

PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C
Aug 1 '08 #17
Steven D'Aprano wrote:
>class A:
def bar(self):
print "A"


Alas, you've chosen the worst-possible example to "clarify" matters,
because old-style classic classes are *not* unified with types, and will
disappear in the future:
Of course I wanted to write `class A(object)', but I keep forgetting
this one because I'm still used to the old ways...

Will this disappear in Python 3.0., i.e. can you again simply write

class A:

and inherit from object automagically? That would be nice since that's
what most people probably want.
Aug 1 '08 #18
Thomas Troeger <th************ ****@siemens.co mwrote:
Will this disappear in Python 3.0., i.e. can you again simply write

class A:

and inherit from object automagically?
Short answer: yes.

-M-

Aug 1 '08 #19


Thomas Troeger wrote:
Steven D'Aprano wrote:
>>class A:
def bar(self):
print "A"


Alas, you've chosen the worst-possible example to "clarify" matters,
because old-style classic classes are *not* unified with types, and
will disappear in the future:

Of course I wanted to write `class A(object)', but I keep forgetting
this one because I'm still used to the old ways...

Will this disappear in Python 3.0., i.e. can you again simply write
class A:
and inherit from object automagically?
Yes.
IDLE 3.0b2
>>class a: pass
>>a
<class '__main__.a'>
>>a.__bases__
(<class 'object'>,)

3.0 is really a nicer version. Once the final release is out, the main
reason to stick with 2.x for new code will be if it depends on
third-party code (including your own ;-) that has not been upgraded.

Aug 1 '08 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3233
by: roopa | last post by:
I have declared a class with name List; and in main() function, i have declared the List object as follows class List { public: List() { cout<<"In List Constuctor";
11
5722
by: Shea Martin | last post by:
I have been programming in C++ for over 4 years. I *think* I knew that a struct could have a constructor but I decided to dig into it a little more today, and found that there is very little difference between a struct and a class in C++. Both have inheritance, access modifiers, etc. The only diff I see is the default access level is public vs. private. I have always just used structs as a minimal class, as that is the way
7
3678
by: yufufi | last post by:
lets say we have a 'shape' class which doesn't implement IComparable interface.. compiler doesn't give you error for the lines below.. shape b= new shape(); IComparable h; h=(IComparable)b; but it complains for the following lines
4
6506
by: ad | last post by:
I am confuse about type and class in some book about C#. What is the difference between type and class?
6
4031
by: JonathanOrlev | last post by:
Hello everyone, I have a newbe question: In Access (2003) VBA, what is the difference between a Module and a Class Module in the VBA development environment? If I remember correctly, new types of objects (classes) can only be defined in Class modules.
12
2394
by: André | last post by:
Hi, i'm learning working with classes. In class "classbase1", i defined an overridable function. In the class "subclass1", i defined the same function with 'Overrides'. In class "classbase2", i defined the same function and in the class "subclass2", i defined the same function with 'Overloads'. Result: i get the same output.
6
2265
by: fcvcnet | last post by:
Hi, I read the book C++ Primer, Fourth Edition By Stanley B. Lippman, Jos¨¦e Lajoie, Barbara E. Moo "If we define a class using the class keyword, then any members defined before the first access label are implicitly private; ifwe usethe struct keyword, then those members are public. Whether we define a class using the class keyword or the struct keyword affects only the default initial access level." Now I defined a struct with...
23
3662
by: Jess | last post by:
Hello, I understand the default-initialization happens if we don't initialize an object explicitly. I think for an object of a class type, the value is determined by the constructor, and for the built-in types, the value is usually garbage. Is this right? However, I'm a bit confused about value-initialization, when does it happen, and what kind of values are assigned to objects?
6
4929
by: mthread | last post by:
Hi, I am learning C++ and I have been told that an object can be created either by using calloc or new. If it is true, can some one tell me what is the difference b/w using these two function calls.
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10039
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9990
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7406
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6668
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5297
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5445
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3560
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2814
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.