Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (20.3k points)

Is it possible to have static class variables or methods in Python? What syntax is required to do this?

2 Answers

0 votes
by (40.7k points)

From anytree import Node, RenderTree try this:

udo = Node("Udo")

marc = Node("Marc", parent=udo)

lian = Node("Lian", parent=marc)

dan = Node("Dan", parent=udo)

jet = Node("Jet", parent=dan)

jan = Node("Jan", parent=dan)

joe = Node("Joe", parent=dan)

print(udo)

Node('/Udo')

print(joe)

Node('/Udo/Dan/Joe')

Here, variables are declared inside the class definition, but not inside a method are class or static variables:

>>> class MyClass:

...     i = 3

...

>>> MyClass.i

Or you can use this:

>>> 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.

class C:

    @staticmethod

    def f(arg1, arg2, ...): ...

0 votes
by (106k points)

You can also add class variables to classes on the fly

>>> class X: 

... pass 

... 

>>> X.bar = 0 

>>> x = X() 

>>> x.bar

>>> x.foo 

Traceback (most recent call last): 

 File "<interactive input>", line 1, in <module> 

AttributeError: X instance has no attribute 'foo' 

>>> X.foo = 1 

>>> x.foo 

1

Related questions

0 votes
1 answer
asked Jul 29, 2019 in Java by Suresh (3.4k points)
0 votes
1 answer
0 votes
1 answer
asked Aug 20, 2019 in Java by Krishna (2.6k points)

Browse Categories

...