-1

All these classes run, and their outward behavior is the same, but I'm not convinced that they are all the same thing (by this I mean indistinguishable except for their names). Unfortunately, I'm not getting any errors by running this code - anyone know what's going on?

--RandNum1--

class RandNum1:
    a = 2

#do stuff

b=RandNum1()
b.a

c=RandNum1
c.a

--RandNum2--

class RandNum2():
    a = 2

#do stuff

b=RandNum2()
b.a

c=RandNum2
c.a

--RandNum3--

class RandNum3(object):
    a = 2

#do stuff

b=RandNum3()
b.a

c=RandNum3
c.a
Alex Walczak
  • 1,276
  • 1
  • 12
  • 27
  • possible duplicate of [Python class inherits object](http://stackoverflow.com/questions/4015417/python-class-inherits-object) – TigerhawkT3 May 30 '15 at 00:55
  • well, there's a bit more. I was wondering if anyone could compare these specific three – Alex Walczak May 30 '15 at 01:05
  • Yes; that's all covered in the answers to that question. – TigerhawkT3 May 30 '15 at 02:26
  • The reason that is not true and why I am leaving this question up is because I'm not asking about old/new-style classes. Rather, it is a question of comparison and explanation of how this code is compiled and run. And I am also asking about more classes. For example, the class RandNum1 is not mentioned anywhere in the referenced question, and if you think you can explain, give it a shot. – Alex Walczak May 30 '15 at 10:24
  • A declaration in the style of your `RandNum1` is given in [this answer](http://stackoverflow.com/a/9448136/2617068) to that question (a new-style class that implicitly inherits from `object`). There are several links in that question's answers that explain the detailed differences. This question is an exact duplicate, and you should have searched. Check out the "Related" sidebar for many questions like this one. – TigerhawkT3 May 30 '15 at 18:19

2 Answers2

1

The third one is a 'new style' class, which is the right way to do class definitions in modern Pythhon 2 (It's not so new anymore, but that's what they are called). In this example the differences won't be apparent, but if you want to do anything complicated with inheritance, property descriptors, introspection, or metaclasses you should use the

class ClassName(object):
      pass

form for the base class and

class DerivedClassName(ClassName):
      pass

form for subclasses.

For more see https://wiki.python.org/moin/NewClassVsClassicClass

theodox
  • 12,028
  • 3
  • 23
  • 36
1

RandNum1 and RandNum2 are exactly, the same, old-style classes with none of the newer object functionalities.

RandNum3, on the other hand, is a new-style class. All things work here.

You should always use new-style classes in most cases, unless what you need is really simple.

noɥʇʎԀʎzɐɹƆ
  • 9,967
  • 2
  • 50
  • 67