开发者

Can I instantiate a new object without using function notation? Why?

If I make a simple class like this:

class Foo:
  i = 1
  j = 2

Can 开发者_如何转开发I instantiate a new object by simply using Foo on the right-hand side ( as opposed to saying Foo() )? I would guess not, but I just tried the following and it worked:

finst = Foo
print finst.i


It works, because i is not a property of the object (or instance) but of the class. You are not creating a new instance.

Try:

class Foo:
  def bar(self):
    print 42

finst = Foo
finst.bar()

Traceback (most recent call last):
File "", line 1, in
TypeError: unbound method bar() must be called with Foo instance as first argument (got nothing instead)


You did not instantiate an object. You just defined a variable in class scope, and accessed it.


Foo by itself is the class object for class Foo:

>>> type(Foo)
<type 'classobj'>
>>> type(Foo())
<type 'instance'>

Your code:

finst = Foo
print finst.i

decodes as:

  1. bind the name finst to the Foo class object.
  2. print the value of the class' attribute i


That's because finst is merely an alias for the class Foo, and i and j are class variables, not instance variables. If you had declared them as instance variables:

class Foo:
    def __init__(self):
        self.i = 1
        self.j = 2

Then your code would cause an error.

To answer your question, no, you must call a constructor to create an instance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜