Do I correctly understand what a class is?

前端 未结 9 985
Happy的楠姐
Happy的楠姐 2021-01-01 20:52

I\'ve had trouble finding a clear, concise laymans definition of a class. Usually, they give general ideas without specifically spelling it out, and I\'m wondering if I\'m u

9条回答
  •  情深已故
    2021-01-01 21:36

    You should look at some sample code, in your language of choice. Just reading about the concept of classes will not answer many questions.

    For example, I could tell you that a class is a "blueprint" for an object. Using this class, you can instantiate multiple such objects, each one of them (potentially) having unique attributes.

    But you didn't understand a thing, now, did you? Your example with the buttons is very limited. Classes have nothing to do with user interfaces or actions or whatever. They define a way of programming, just like functions/methods/whatever you want to call them do.

    So, to give a concrete example, here's a class that defines a ball, written in Python:

    class Ball:
        color = ''
        def __init__(self, color):
            self.color = color
        def bounce(self):
            print "%s ball bounces" % self.color
    
    blueBall = Ball("blue")
    redBall = Ball("red")
    
    blueBall.bounce()
    redBall.bounce()
    

    Running this produces the expected output:

    blue ball bounces
    red ball bounces
    

    However, there is much more to classes than I described here. Once you understand what a class is, you go on to learn about constructors, destructors, inheritance and a lot of other good stuff. Break a leg :)

提交回复
热议问题