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

3
  • 3
    Does the code you posted do what you expected? Commented Aug 24, 2019 at 16:42
  • 1
    Possible duplicate of Adding new member variables to python objects? Commented Aug 24, 2019 at 16:58
  • @khelwood Yes it is. Commented Aug 25, 2019 at 16:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Nick Reed. Now I understand this.
@FahadIqbalKhan Very glad to help! Please consider accepting the answer if it properly addresses your question, and good luck with the rest of your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.