creating Object
class GameObject:
# the initializer function
def __init__(self, name, x_pos, y_pos):
self.name = name
self.x_pos = x_pos
self.y_pos = y_pos
# create a new game object
game_object = GameObject("Enemy", 1, 2)
# access the properties of the game object
print(game_object.name)
# change game object properties to new values
game_object.name = "Enemy 1"
Object
add functions & refences
# implement a move function
def move(self, by_x_amount, by_y_amount):
self.x_pos += by_x_amount
self.y_pos += by_y_amount
# accessing more properties of the game object
print(game_object.x_pos)
print(game_object.y_pos)
# use the new move function to change x and y positions of the game object
game_object.move(5, 10)
# check the new position
# create a different game object with the same class
other_game_object = GameObject("Player", 2, 0)
# access the properties of the new game object
print(other_game_object.name)
print(other_game_object.x_pos)
print(other_game_object.y_pos)
# example of value types
one_int = 5
another_int = one_int # value is copied
print(one_int)
print(another_int)
another_int = 10 # only this value is changed
# example of reference types with objects
other_game_object = game_object # a reference to the original game object
other_game_object.name = "new name" # properties in both objects are changed
Inheritance
class GameObject: # this is now the superclass
# create a subclass that inherits from GameObject class
class Enemy(GameObject):
# implement different initializer function with additional attributes
def __init__(self, name, x_pos, y_pos, health):
super().__init__(name, x_pos, y_pos)
self.health = health
# implement function to reduce health
def take_damage(self, amount):
self.health -= amount
game_object = GameObject("Game object", 1, 2)
# create an enemy object
enemy = Enemy("Enemy", 5, 10, 100)
print(enemy.name)
# only the subclass has access to the new take_damage function
enemy.take_damage(20)
print(enemy.health)
Zuletzt geändertvor einem Jahr