0% found this document useful (0 votes)
258 views

Learn Python 3 - Classes Cheatsheet - Codecademy

The document discusses key concepts in Python classes including: 1) The __repr__() method returns a string representation of a class instance. The init() method initializes newly created class objects. Class methods take self as the first argument. 2) Classes are defined using the class keyword. Instances of a class are created using class_name(). Class variables are shared among all instances while instance variables are unique to each object. 3) The dir() function returns a list of valid attributes of an object. __main__ refers to the current module. super() allows calling a parent method from a child class. Polymorphism allows using child and parent classes interchangeably.

Uploaded by

Joe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
258 views

Learn Python 3 - Classes Cheatsheet - Codecademy

The document discusses key concepts in Python classes including: 1) The __repr__() method returns a string representation of a class instance. The init() method initializes newly created class objects. Class methods take self as the first argument. 2) Classes are defined using the class keyword. Instances of a class are created using class_name(). Class variables are shared among all instances while instance variables are unique to each object. 3) The dir() function returns a list of valid attributes of an object. __main__ refers to the current module. super() allows calling a parent method from a child class. Polymorphism allows using child and parent classes interchangeably.

Uploaded by

Joe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Cheatsheets / Learn Python 3

Classes
Python repr method
The Python __repr__() method is used to tell
Python what the string representation of the class should class Employee:
be. It can only have one parameter, self , and it should def __init__(self, name):
return a string. self.name = name

def __repr__(self):
return self.name

john = Employee('John')
print(john) # John

Python class methods


In Python, methods are functions that are de ned as part
of a class. It is common practice that the rst argument of # Dog class
any method that is part of a class is the actual object class Dog:
calling the method. This argument is usually called self. # Method of the class
def bark(self):
print("Ham-Ham")

# Create a new instance


charlie = Dog()

# Call the method


charlie.bark()
# This will output "Ham-Ham"

Instantiate Python Class


In Python, a class needs to be instantiated before use.
As an analogy, a class can be thought of as a blueprint class Car:
(Car), and an instance is an actual implementation of the "This is an empty class"
blueprint (Ferrari). pass

# Class Instantiation
ferrari = Car()

/
Python Class Variables
In Python, class variables are de ned outside of all
methods and have the same value for every instance of class my_class:
the class. class_variable = "I am a Class
Class variables are accessed with the Variable!"
instance.variable or
class_name.variable syntaxes. x = my_class()
y = my_class()

print(x.class_variable) #I am a Class
Variable!
print(y.class_variable) #I am a Class
Variable!

Python init method


In Python, the .__init__() method is used to
initialize a newly created object. It is called every time the class Animal:
class is instantiated. def __init__(self, voice):
self.voice = voice

# When a class instance is created, the


instance variable
# 'voice' is created and set to the input
value.
cat = Animal('Meow')
print(cat.voice) # Output: Meow

dog = Animal('Woof')
print(dog.voice) # Output: Woof

Python type() function


The Python type() function returns the data type of
the argument passed to it. a = 1
print(type(a)) # <class 'int'>

a = 1.1
print(type(a)) # <class 'float'>

a = 'b'
print(type(a)) # <class 'str'>

a = None
print(type(a)) # <class 'NoneType'>

/
Python class
In Python, a class is a template for a data type. A class can
be de ned using the class keyword. # Defining a class
class Animal:
def __init__(self, name,
number_of_legs):
self.name = name
self.number_of_legs = number_of_legs

Python dir() function


In Python, the built-in dir() function, without any
argument, returns a list of all the attributes in the current class Employee:
scope. def __init__(self, name):
With an object as argument, dir() tries to return all self.name = name
valid object attributes.
def print_name(self):
print("Hi, I'm " + self.name)

print(dir())
# ['Employee', '__builtins__', '__doc__',
'__file__', '__name__', '__package__',
'new_employee']

print(dir(Employee))
# ['__doc__', '__init__', '__module__',
'print_name']

__main__ in Python
In Python, __main__ is an identi er used to reference
the current le context. When a module is read from
standard input, a script, or from an interactive prompt, its
__name__ is set equal to __main__ .
Suppose we create an instance of a class called
CoolClass . Printing the type() of the instance
will result in:

<class '__main__.CoolClass'>

This means that the class CoolClass was de ned in


the current script le.

/
Super() Function in Python Inheritance
Python’s super() function allows a subclass to invoke
its parent’s version of an overridden method. class ParentClass:
def print_test(self):
print("Parent Method")

class ChildClass(ParentClass):
def print_test(self):
print("Child Method")
# Calls the parent's version of
print_test()
super().print_test()

child_instance = ChildClass()
child_instance.print_test()
# Output:
# Child Method
# Parent Method

User-de ned exceptions in Python


In Python, new exceptions can be de ned by creating a
new class which has to be derived, either directly or class CustomError(Exception):
indirectly, from Python’s Exception class. pass

Polymorphism in Python
When two Python classes o er the same set of methods
with di erent implementations, the classes are class ParentClass:
polymorphic and are said to have the same interface. An def print_self(self):
interface in this sense might involve a common inherited print('A')
class and a set of overridden methods. This allows using
the two objects in the same way regardless of their
class ChildClass(ParentClass):
individual types.
def print_self(self):
When a child class overrides a method of a parent class,
print('B')
then the type of the object determines the version of the
method to be called. If the object is an instance of the
child class, then the child class version of the overridden obj_A = ParentClass()
method will be called. On the other hand, if the object is obj_B = ChildClass()
an instance of the parent class, then the parent class
version of the method is called. obj_A.print_self() # A
obj_B.print_self() # B

/
Dunder methods in Python
Dunder methods, which stands for “Double Under”
(Underscore) methods, are special methods which have class String:
double underscores at the beginning and end of their # Dunder method to initialize object
names. def __init__(self, string):
We use them to create functionality that can’t be self.string = string
represented as a normal method, and resemble native
Python data type interactions. A few examples for dunder
string1 = String("Hello World!")
methods are: __init__ , __add__ , __len__ ,
print(string1.string) # Hello World!
and __iter__ .
The example code block shows a class with a de nition
for the __init__ dunder method.

Method Overriding in Python


In Python, inheritance allows for method overriding,
which lets a child class change and rede ne the class ParentClass:
implementation of methods already de ned in its parent def print_self(self):
class. print("Parent")
The following example code block creates a
ParentClass and a ChildClass which both class ChildClass(ParentClass):
de ne a print_test() method. def print_self(self):
As the ChildClass inherits from the print("Child")
ParentClass , the method print_test() will
be overridden by ChildClass such that it prints the child_instance = ChildClass()
word “Child” instead of “Parent”. child_instance.print_self() # Child

Python Inheritance
Subclassing in Python, also known as “inheritance”, allows
classes to share the same attributes and methods from a class Animal:
parent or superclass. Inheritance in Python can be def __init__(self, name, legs):
accomplished by putting the superclass name between self.name = name
parentheses after the subclass or child class name.
self.legs = legs
In the example code block, the Dog class subclasses
the Animal class, inheriting all of its attributes. class Dog(Animal):
def sound(self):
print("Woof!")

Yoki = Dog("Yoki", 4)
print(Yoki.name) # YOKI
print(Yoki.legs) # 4
Yoki.sound() # Woof!

/
+ Operator
In Python, the + operation can be de ned for a user-
class A:
de ned class by giving that class an .__add()__
method.
def __init__(self, a):
self.a = a
def __add__(self, other):
return self.a + other.a

obj1 = A(5)
obj2 = A(10)
print(obj1 + obj2) # 15

Python issubclass() Function


The Python issubclass() built-in function checks
if the rst argument is a subclass of the second argument. class Family:
In the example code block, we check that Member is a def type(self):
print("Parent class")
subclass of the Family class.

class Member(Family):
def type(self):
print("Child class")

print(issubclass(Member, Family)) # True

You might also like