The differences between a class
and a struct
in C++ is:
struct
members and base classes/structs are public
by default.
class
members and base classes/struts are private
by default.
Both classes and structs can have a mixture of public
, protected
and private
members, can use inheritance and can have member functions.
I would recommend you:
- use
struct
for plain-old-data structures without any class-like features;
- use
class
when you make use of features such as private
or protected
members, non-default constructors and operators, etc.
Variables declared inside the class definition, but not inside a method are class or static variables:
>>> class MyClass:
... i = 3
...
>>> MyClass.i
3
As @millerdev points out, this creates a class-level i
variable, but this is distinct from any instance-level i
variable, so you could have
>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)
This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance.
See what the Python tutorial has to say on the subject of classes and class objects.
@Steve Johnson has already answered regarding static methods, also documented under "Built-in Functions" in the Python Library Reference.
class C:
@staticmethod
def f(arg1, arg2, ...): ...
@beidy recommends classmethods over staticmethod, as the method then receives the class type as the first argument, but I'm still a little fuzzy on the advantages of this approach over staticmethod. If you are too, then it probably doesn't matter.
Best Answer
It all comes down to how you create the parent object.
Heaps and stacks are of course an implementation detail, but in this case I think it's fair to specify.