New-style classes were introduced in Python 2.2 to unify classes and types. A new-style class is neither more nor less than a user-defined ...
Lessthan10daystoRSVP!Virtuallyjoinusatourinauguralconference,everyoneiswelcome.
Home
Public
Questions
Tags
Users
Companies
Collectives
ExploreCollectives
Teams
StackOverflowforTeams
–Startcollaboratingandsharingorganizationalknowledge.
CreateafreeTeam
WhyTeams?
Teams
CreatefreeTeam
Collectives™onStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
LearnmoreaboutCollectives
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
LearnmoreaboutTeams
typeofclassinpython
AskQuestion
Asked
11years,11monthsago
Modified
11years,11monthsago
Viewed
5ktimes
2
whyifIdo:
classC():pass
type(C())
Igot:,butifIdo:
classC(object):pass
type(c())
Igot:?
Thefirstisnotveryuserfull
pythonclasstypesnew-style-class
Share
Improvethisquestion
Follow
askedOct7,2010at21:44
RuggeroTurraRuggeroTurra
15.9k1414goldbadges8686silverbadges133133bronzebadges
1
Whatdoyouwanttohaveinstead?Whatisnotuseful?Thatitisdifferent?
– FelixKling
Oct7,2010at21:53
Addacomment
|
1Answer
1
Sortedby:
Resettodefault
Highestscore(default)
Trending(recentvotescountmore)
Datemodified(newestfirst)
Datecreated(oldestfirst)
3
Lookupthedifferencebetweenold-styleandnew-styleclasses.Theformerarethedefault,andthelatterinheritexplicitlyfromobject.
Allold-styleobjectswereimplementedwiththebuilt-intypeinstance.Thefactthattheyarestillthedefaultandtheirtyperemains'instance'isaresultofretro-compatibilityprecautions.
ThisisextractedfromthePythondocs(http://docs.python.org/reference/datamodel.html)
3.3.New-styleandclassicclassesClassesandinstancescomeintwo
flavors:old-style(orclassic)and
new-style.
UptoPython2.1,old-styleclasses
weretheonlyflavouravailabletothe
user.Theconceptof(old-style)class
isunrelatedtotheconceptoftype:
ifxisaninstanceofanold-style
class,thenx.classdesignatesthe
classofx,buttype(x)isalways
.Thisreflectsthe
factthatallold-styleinstances,
independentlyoftheirclass,are
implementedwithasinglebuilt-in
type,calledinstance.
New-styleclasseswereintroducedin
Python2.2tounifyclassesandtypes.
Anew-styleclassisneithermorenor
lessthanauser-definedtype.Ifxis
aninstanceofanew-styleclass,then
type(x)istypicallythesameas
x>.class(althoughthisisnot
guaranteed-anew-styleclass
instanceispermittedtooverridethe
valuereturnedforx.class).
Themajormotivationforintroducing
new-styleclassesistoprovidea
unifiedobjectmodelwithafull
meta-model.Italsohasanumberof
practicalbenefits,liketheability
tosubclassmostbuilt-intypes,or
theintroductionof“descriptors”,
whichenablecomputedproperties.
Forcompatibilityreasons,classesare
stillold-stylebydefault.New-style
classesarecreatedbyspecifying
anothernew-styleclass(i.e.atype)
asaparentclass,orthe“top-level
type”objectifnootherparentis
needed.Thebehaviourofnew-style
classesdiffersfromthatofold-style
classesinanumberofimportant
detailsinadditiontowhattype()
returns.Someofthesechangesare
fundamentaltothenewobjectmodel,
likethewayspecialmethodsare
invoked.Othersare“fixes”thatcould
notbeimplementedbeforefor
compatibilityconcerns,likethe
methodresolutionorderincaseof
multipleinheritance.
Whilethismanualaimstoprovide
comprehensivecoverageofPython’s
classmechanics,itmaystillbe
lackinginsomeareaswhenitcomesto
itscoverageofnew-styleclasses.
Pleasesee
http://www.python.org/doc/newstyle/
forsourcesofadditionalinformation.
Old-styleclassesareremovedin
Python3.0,leavingonlythesemantics
ofnew-styleclasses.ofnew-styleclasses.
Share
Improvethisanswer
Follow
answeredOct7,2010at21:52
slezicaslezica
71.2k2424goldbadges9797silverbadges162162bronzebadges
1
youneedtoedityouranswerandchangeallyour"x.__class__"into"`x.__class__`"
– tzot
Oct9,2010at1:19
Addacomment
|
YourAnswer
ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers.
Draftsaved
Draftdiscarded
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingEmailandPassword
Submit
Postasaguest
Name
Email
Required,butnevershown
PostYourAnswer
Discard
Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy
Nottheansweryou'relookingfor?Browseotherquestionstaggedpythonclasstypesnew-style-classoraskyourownquestion.
TheOverflowBlog
IspenttwoyearstryingtodowhatBackstagedoesforfree
Aserialentrepreneurfinallyembracesopensource(Ep.486)
FeaturedonMeta
PlannedmaintenancescheduledforWednesday,21September,00:30-03:00UTC...
RecentColorContrastChangesandAccessibilityUpdates
Revieweroverboard!Orarequesttoimprovetheonboardingguidancefornew...
ShouldIexplainotherpeople'scode-onlyanswers?
Related
2403
StaticclassvariablesandmethodsinPython
6952
WhataremetaclassesinPython?
1685
What'sthecanonicalwaytocheckfortypeinPython?
7476
DoesPythonhaveaternaryconditionaloperator?
2046
HowtodetermineaPythonvariable'stype?
1836
Gettingtheclassnameofaninstance
3453
Convertbytestoastring
3205
"LeastAstonishment"andtheMutableDefaultArgument
1274
Whatisthepurposeofthe`self`parameter?Whyisitneeded?
2800
Whyis"1000000000000000inrange(1000000000000001)"sofastinPython3?
HotNetworkQuestions
CanmyUKcompanyordermetojoinasocialevent?
Isthereawayquerythedenominationinformationofasubstratetokenfromtheruntime?
LTspicecapacitorbug?
110.15High-LegMarking
Arethereradiosystemsthatallowpeopletotalksimultaneously?
Multiplyplantfrommotherplant
PhDinaprobablyhopelessresearchproject
Inaircraftreliabilitymonitoringanalysis,whythecalculationofdefectrateisper1000FH?
EachhaveorHaveeach
Dowesay"abarofstaples"?
Howtomakedefinedlabelsontopoftheedgeinagraphwithtikz?
Scholarshipsbyemailingprofessors
Howtopronounce"Gröbner"?
Whereisthereactionforceofanobjectthathasjustflungoutfromacircularmotion?
HasNASAreleasedanyJWSTimagesofTrappist-1?Ifnot,why?
UsingQGISFieldCalculatorondelimiterseparatedvalues
Somethingappearsvaluableorpreciousbutitisn't,symbolicallyequivalenttoPyrite?
IsitachievabletokeepallofHalacha?
Whatdoesitmeantonothavepointsinavatar?
Wordsforrelativeorientationofsidesofdouble-sidedpaper?
Whyisthe-eoptionnotinthebashcommandmanual?
AsaPhDstudentintheoreticalphysics,whatfractionofmytime(ifany)shouldIspendonbackgroundmaterialratherthanmyresearchproblem?
Chessetiquette:Carlsenwithdrawingfromthetournament
InwhichtournamentdidKarpovplayhisfirstmovewithwhitepiecesandofferadraw?
morehotquestions
Questionfeed
SubscribetoRSS
Questionfeed
TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader.
lang-py
Yourprivacy
Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy.
Acceptallcookies
Customizesettings