# Equivalent Julia code for a Python class with counter variables

**URL:** <https://discourse.julialang.org/t/equivalent-julia-code-for-a-python-class-with-counter-variables/115385>\
**Category:** General Usage\
**Tags:** python\
**Created:** [June 9, 2024, 9:02am UTC](https://discourse.julialang.org/t/equivalent-julia-code-for-a-python-class-with-counter-variables/115385 "2024-06-09T09:02:03Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Shuvomoy\_Das\_Gupta](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/shuvomoy_das_gupta/32/10069_2.png) [@Shuvomoy\_Das\_Gupta](https://discourse.julialang.org/u/Shuvomoy_Das_Gupta)\
**Post date:** [June 9, 2024, 9:02am UTC](https://discourse.julialang.org/t/equivalent-julia-code-for-a-python-class-with-counter-variables/115385/1 "2024-06-09T09:02:03Z")

</div>

Consider the following Python code from the [link](https://stackoverflow.com/questions/10005343/counter-variable-for-class)

```julia
# Python code
class Student:
    # A student ID counter
    idCounter = 0
    def __init__ (self):
        self.gpa = 0
        self.record = {}
        # Each time I create a new student, the idCounter increment
        Student.idCounter += 1
        self.name = 'Student {0}'.format(Student.idCounter)

classRoster = [] # List of students
for number in range(25):
    newStudent = Student()
    classRoster.append(newStudent)
    print(newStudent.name)

```

What would be the best way to implement this equivalently in Julia, preferably using `mutable struct`? Any tips/best practices will be much appreciated.

---

<div class="post-metadata">

**Author:** ![GunnarFarneback](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gunnarfarneback/32/1827_2.png) [@GunnarFarneback](https://discourse.julialang.org/u/GunnarFarneback)\
**Post date:** [June 9, 2024, 9:20am UTC](https://discourse.julialang.org/t/equivalent-julia-code-for-a-python-class-with-counter-variables/115385/2 "2024-06-09T09:20:54Z")

</div>

This is one possibility:

```julia
mutable struct Student
    gpa::Int
    record::Dict{Any, Any}
    name::String
end

let counter = 0
    global function Student()
        counter += 1
        return Student(0, Dict(), "Student $counter")
    end
end

```

---

<div class="post-metadata">

**Author:** ![Shuvomoy\_Das\_Gupta](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/shuvomoy_das_gupta/32/10069_2.png) [@Shuvomoy\_Das\_Gupta](https://discourse.julialang.org/u/Shuvomoy_Das_Gupta)\
**Post date:** [June 9, 2024, 9:30am UTC](https://discourse.julialang.org/t/equivalent-julia-code-for-a-python-class-with-counter-variables/115385/3 "2024-06-09T09:30:03Z")

</div>

Thanks, that works.
