/ W3SCHOOLS

W3schools - Python_Class

이 페이지는 다음에 대한 공부 기록입니다
Lecture에서 배웠던 내용을 복습하며 작성했습니다

찾으시는 정보가 있으시다면
주제별reference를 이용하시거나
우측 상단에 있는 검색기능을 이용해주세요

Classes / Objects

Python is an OOP langs

Almost everything in Python is an object, with its properties and methods

Class is like an object constructor, or a “blueprint” for creating objects

# Create a class
class MyClass:
    x = 5

# Create object
p1 = MyClass()
print(p1.x)	# output 5

init()

All classes have a func called init(), which is always executed when the class is being initiated

Use the init() to assign values to object properties, or other operations that are necessary to do when the object is being created

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
p1 = Person(Sponge, 20)

print(p1.name)	# output “Sponge”
print(p1.age)		# output 20

self Parameter

Is reference to the current instance of the class, and is used to access var that belongs to the class

It doesn’t have to be named “self”, can call it whatever you like, but it has to be the first parameter of any func in the class

class Person:

    def__init__(silly, name, age):		# Use the words silly, abc instead of self
        silly.name = name
        silly.age = age
        
    def func(abc):		# Object can also contain methods. methods in objects are funcs that belong to the object
        print(Hello  + abc.name)
        
p1 = Person(Sponge, 20)
p1.func()	# output “Hello Sponge”
p1.age = 40	# Can modify properties on object
print(p1.age)		# output 40
del p1.age	# delete Object Properties
print(p1.age)		# error

Inheritance

Allows us to define a class that inherits all the methods and properties from another class

Parent class is the class being inherited from, also called base class

Child class is the class that inherits from another class, also called derived class

  • To create a class that inherits the functionality from another class, send the parent class as a param when creating the child class
# Parent class
class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

	def printname(self):
		print(self.firstname, self.lastname)

# Child class
class Student(Person):
    pass	# Use the pass keyword when don’t want to add any other properties or methods to the class
    
x = Student(Sponge, Bob)
x.printname()		# output “Sponge Bob”

When you add the __init__(), the child class will no longer inherit the parent’s __init()__

  • The child’s __init__() overrides the inheritance of the parent’s __init__()

  • To keep the inheritance of the parent’s __init__(), add a call to the parent’s __init__()

class Student(Person):
    def __init__(self, fname, lname):
        super().__init__(fname, lname)	# By using the super(), don’t have to use the name of the parent element
        self.year = 2022	# Can add properties

Iterator

Is an object that contains a countable number of values

Is an object that can be iterated upon, meaning that you can traverse through all the values

Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__()

You can get an iterator from iterable containers(list, tuples,…)

  • All these objects have a iter() which is used to get an iterator

for loop actually creates an iterator object and executes the next() for each loop

tuple = (apple, banana)
myit = iter(tuple)

print(next(myit))	# output “apple”
print(next(myit))	# output “banana”

Create iterator

To create an object/class as an iterator, you have to implement the methods __iter__() and __next__() to your object

__iter__() acts similar to __init__(), you can do operations(initializing etc.), but must always return the iterator object itself

__next__() also allows to do operations, and must return the next item in the sequence

class Numbers:
    def __iter__(self):
        self.a = 1
        return self

    def __next__(self):
        if self.a < 4
            x = self.a
            self.a += 1
            return x
        else:
            raise StopIteration	# To prevent the iteration to go on forever, use the StopIteration statement

myclass = Numbers()
myiter = iter(myclass)

print(next(myiter))	# output 1
print(next(myiter)) 	# output 2
print(next(myiter)) 	# output 3
print(next(myiter))	# error