Python Forum
What colon (:) in Python mean in this case?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What colon (:) in Python mean in this case?
#4
I guess it can be type notation for a class variable. Syntactically that is correct. Logically it doesn't make any sense.

So we have our class Point, a singleton that requires we make instances so they can be passed to where_is() to demonstrate how match works.
class Point():
    x: int
    y: int

def where_is(point):
    match point:
        case Point(x=0, y=0):
            print("Origin")
        case Point(x=0, y=y):
            print(f"Y={y}")
        case Point(x=x, y=0):
            print(f"X={x}")
        case Point():
            print("Somewhere else")
        case _:
            print("Not a point")

point = Point()
where_is(point)
Point.x, Point.y = 0, 0
where_is(point)
Point.x, Point.y = 0, 1
where_is(point)
Point.x, Point.y = 1, 0
where_is(point)
where_is((0, 0))
That is just ugly. If the ": int" really is type annotation for class variables, this is a bad example.

It works better, but is longer, if x and y are properties.
class Point():
    def __init__(self, x=None, y=None):
        self._x, self._y = x, y

    @property
    def x(self) -> int:
        return self._x

    @x.setter
    def x(self, value: int):
        self._x = value

    @property
    def y(self) -> int:
        return self._y

    @y.setter
    def y(self, value: int) :
        self._y = value

 
def where_is(point):
    match point:
        case Point(x=0, y=0):
            print("Origin")
        case Point(x=0, y=y):
            print(f"Y={y}")
        case Point(x=x, y=0):
            print(f"X={x}")
        case Point():
            print("Somewhere else")
        case _:
            print("Not a point")
 
where_is(Point(0, 0))
where_is(Point(0, 1))
where_is(Point(1, 0))
where_is(Point())
where_is((0, 0))
Reply


Messages In This Thread
RE: What colon (:) in Python mean in this case? - by deanhystad - Dec-28-2022, 10:41 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  remove colon if value is None wardancer84 7 2,033 Feb-02-2022, 02:32 PM
Last Post: ibreeden
  Switch case or match case? Frankduc 9 4,711 Jan-20-2022, 01:56 PM
Last Post: Frankduc
  Logstash - sending Logstash messages to another host in case of Failover in python Suriya 0 1,706 Jul-27-2021, 02:02 PM
Last Post: Suriya
  Help: write 'case' with Python ICanIBB 2 1,925 Jan-27-2021, 09:39 PM
Last Post: Larz60+
  How to use switch/case in python? newbieguy 9 4,202 Nov-08-2019, 11:35 AM
Last Post: newbieguy
  How to write switch case statement in Python pyhelp 9 9,387 Nov-11-2018, 08:53 PM
Last Post: woooee
  Is there a something like "case" in Python 3.6? Raptor88 18 21,152 Feb-27-2017, 02:44 AM
Last Post: Raptor88

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020