-1

Is it possible to create and initialize an instance variable after initializing a class?

class Point:
    def move(self):
        print("Move")
    def draw(self):
        print("Draw")

point1 = Point()
point1.x = 10
point1.y = 20
print("X: " + point1.x)
print("Y: " + point1.y)

I am beginner to Python and it's a little concept that I cannot get at this time.

khelwood
  • 55,782
  • 14
  • 81
  • 108

1 Answers1

1

It sure is! From the python docs: "Sometimes it is useful to have a data type similar to the Pascal “record” or C “struct”, bundling together a few named data items. An empty class definition will do nicely."

Python lets you add elements to your defined classes after you've defined them. Your code (with a slight modification; as written, you need a comma instead of a plus in your print statements) will compile and run without issue. In fact, here's your code running online. Looks good to me!

That's not all, though. Python classes are more or less "fancy dict wrappers", which is to say, you can store all sorts of things in them after they're instantiated. In fact, you can even define functions and store them in the class. Python's really flexible.

Nick Reed
  • 4,989
  • 4
  • 17
  • 37