Learn Python the Hard Way: exercise 40 - what is "object" and "self" in class definition? -
below code learn python hard way exercise 40: modules, classes, , objects can't seem figure out why there parameter class mystuff(object). what's reason put object in parentheses?
class mystuff(object): def __init__(self): self.tangerine = "and thousand years between" def apple(self): print "i classy apples!"
i have looked through of articles here on stackoverflow failed understand what's new object , old class object. please explain meaning of object
in class definition? happens if leave parentheses empty when declare class?
also there (self) argument 2 functions in code.
in book says "self" empty object python created while instantiating object class.
why stating argument before actual use of it??
i have been learning programming 2 weeks apologize if question superficial, thank time~
as per comment, see using python 2. in python 2.2 introduced "new-style" classes, kept "classic" classes backwards-compatibility reasons. in python 3.0 or newer, classic classes gone - every class new-style class (regardless of syntax).
for python 2.2-2.7, syntactically new-style class declared subclassing object
explicitly (unless has different parent class):
class mystuffnew(object): a=1
while omitting object
reference creates classic class:
class mystuffclassic(): a=1
functionally, work same, there few differences between them in builtin language definitions. example, new-style classes introduced builtin class method __mro()__
(method resolution order) used interpreter work out method (in class inheritance heirarchy) meant call. inbuilt method missing in old-style classes (and method resolution order different, can lead unexpected behaviour). more information new-style vs classic classes, please read this python wiki page.
as mentioned above, in python3 or above, syntax used doesn't matter; classes new-style. however, many coders use class myclass(object):
syntax maintain code compatibility python2.7. - please see this answer.
in version of python language, class mychildclass(parentclass):
defines inheritance relationship - mychildclass
child of parentclass
, inherit of methods , fields.
the self
way python knows member method , not static function of class. can access member fields , methods within class using self.field
, self.mymethod(var1,var2)
, etc.
when call these functions other places in code, don't pass value self
- variable using. example:
stuff = mystuff() stuff.apple() # outputs "i classy apples!" print stuff.tangerine # outputs "and thousand years between" stuff.tangerine = "something else." print stuff.tangerine # outputs "something else." stuff2 = mystuff() print stuff2.tangerine # outputs "and thousand years between"
if don't include self
in method definition, calling mystuff.apple()
result in runtime error because implicitly it's same thing calling mystuff.apple(mystuff)
- passing instance of mystuff
class apple function.
Comments
Post a Comment