Classes

  • ues classes to define new types to model real concepts
  • the new type has the methods for working with this class
  • use lower case letters to name variables and functions and separate mutiple words using an under-square. Use capitalized-first-letter to separate mutiple words
  • use a colomn to define a block
  • objects can have methods we define in calss block and attributes(variables belong to a particular object), each object is a different instance of a class
class Point:
    def move(self):
        print('move')

    def draw(self):
        print('draw')


point1 = Point()
point1.x = 10
point1.y = 20
point1.draw()
print(point1.x)
  • a consturctor is a function that gets codes at the time of creating an object
    • init is the function or the method that is called when we create a new object
    • self is a reference to the current object
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def move(self):
        print('move')

    def draw(self):
        print('draw')


point1 = Point(10,11)

Exercise: building a Person class that contains a name attribute and a talk method

class Person:
    def __init__(self, name):
        self.name = name

    def talk(self):
        print(f'Hi, I am {self.name}')


person1 = Person('Mary')
person1.talk()

你可能感兴趣的:(Classes)