Define function on a subdomain?

Hello,
I’m pretty new in FEniCS (python) and still learning.
I think mine is a simple problem, but I can’t figure it out even after reading many other questions.
I created a mesh with two different subdomains (marked with 1 and 2). Let’s say that I need to define a function that is 1 in subdomain 1 and 0 in subdomain 2. How can I do that efficiently?
It’s quite impossible doing that using class(UserExpression) with eval method because the subdomains have complex geometries (same thing using Expression). Also I tried (unsuccessfully) eval_cell() method as show here https://fenicsproject.org/pub/tutorial/sphinx1/._ftut1005.html

Thank you for the help

Take a look at the following example:

from dolfin import *

# Get mesh with subdomains marked 0 and 1
# in a `MeshFunction` object:
from mshr import *
square = Rectangle(Point(-1,-1),Point(1,1))
circle = Circle(Point(0,0),0.5)
square.set_subdomain(1,circle)
mesh = generate_mesh(square,16)
markers = MeshFunction("size_t",mesh,
                       mesh.topology().dim(),
                       mesh.domains())

# Create `UserExpression` corresponding to
# characteristic function of sub-domain 1:
class CharacteristicFunction(UserExpression):
    def eval_cell(self, values, x, cell):
        if(markers[cell.index] == 0):
            values[0] = 0
        else:
            values[0] = 1
    def value_shape(self):
        return ()

# Project onto a DG0 space and visualize:
f = project(CharacteristicFunction(),
            FunctionSpace(mesh,"DG",0))
from matplotlib import pyplot as plt
plot(mesh)
plot(f)
plt.show()

Thank you so much.
Your example is similar to the one I found in the FEniCS documentation, but I think there is a problem when I try to pass the function values and subdomains.
If I use the following code

k0  =   0   
k1  =   1   
class K(UserExpression):
    def __init__(self, subdomains, k0, k1, **kwargs):
        self.subdomains = subdomains
        self.k0 = k0
        self.k1 = k1
    
    def eval_cell(self, values, x, cell):
        if self.subdomains[cell.index] == 1:
            values[0] = self.k0
    
        if self.subdomains[cell.index] == 2:
            values[0] = self.k1
    
    def value_shape(self):
        return ()

kappa = K(subdomains, k0, k1) 
W   =   FunctionSpace(mesh, 'DG', 0)
u1  =   project(kappa, W)

I get this error:

AttributeError: 'K' object has no attribute '_ufl_shape'

You know why?

Thank you so much again

You need to add: super().__init__(**kwargs) to your __init__ function.

thank you so much.
Now it works