CodeRef
CodeRef
  • Software
    • VSCode
  • Midjourney_AI
    • Midjourney Cheat Sheet
  • aws
    • S3 Reference
    • Services
  • bash
    • .bashrc File Contents
    • CAN
    • _System Config File Locations
    • argument-length-limits
    • Conditionals
    • Data Structures
    • File Permissions
    • File Syncing
    • File System
    • Functions
    • General
    • Loops
    • My Functions
    • Networking
    • Number Operations
    • OpenVPN
    • Operators
    • Resource Management
    • Serial RS232
    • Spinning Wheel Animation
    • SSH
    • Text Operations
    • Environment Variables
  • cpp
    • ChatGPT | Pointers vs. References
    • arrays
    • Classes
    • Data Types / Structures
    • Enumerated Classes
    • Exception Handling
    • Function Objects
    • Functions
    • I/O
    • Loops
    • Macros
    • Namespaces
    • New Features
    • Pointers
    • Scope
    • Smart Pointers
    • Raw String Literals
    • Style Guide
    • Switch Case
    • Templating
    • How to Use tinyxml2
    • Useful Libraries
    • google-test
    • Conditionals
    • Rule of Three/Five
    • Optional Parameters
    • Keywords
    • Filesystem
    • Random
    • Casting
    • tools
  • git
    • Code Review Dependency Strategy
    • Git Bisect Guide
    • Git Reference
    • removing-cherry-picks
    • Useful Tools
    • Graphite Reference
  • js
    • functions
    • Javascript Reference
  • linux
    • Display
    • Dual Boot with Windows
    • File System
    • NVIDIA
    • Sending/Receiving TCP/UDP Messages in Ubuntu
    • dynamically_linked_binaries
  • markdown
    • Images
    • obsidian-reference
  • python
    • Classes
    • Exceptions
    • Functions
    • Operations
    • Python Reference
    • unittest_command-line-args
    • unittest_magicmock_GPT
    • unittest_mock
    • unittest_printing
    • unittest_subtest
    • useful-stuff
    • jupyter
    • poetry
  • ros
    • _ROS Cheat Sheet
    • Create New Workspace
    • Install ROS
    • Node Sample - Listener
    • Node Sample - Talker
    • Node Template
    • Setup
    • urdf
  • excel
    • excel-reference
  • windows
    • File System
    • WSL - Windows Subsystem for Linux
    • WSL
  • software_engineering
    • uncle_bob_lectures
      • Overview
      • Lesson 01 - Notes
  • web
    • Front End
    • Hugo
    • new_frontend_tools
  • sql
    • cheatsheet
Powered by GitBook
On this page
  • Reference Table
  • Define a Class
  • Member Variables
  • Methods
  • Accessing from Outside
  • Accessing from Inside
  • Using Attribute Functions
  1. python

Classes

Reference Table

No Instance / Class Level
With Instance / Instance Level

Prefix Convention

cls

self

Define Variable

cls.var1 = 0

self.var1 = 0

Define Method

Access Class Attribute from Outside Class

Access Class Attribute from Inside Class

Access Instance Variable from Outside Class

Not possible

Access Instance Variable from Inside Class

Not possible

Call Class Method from Outside Class

Call Class Method from Inside Class

Call Regular Method from Outside Class

Not possible

Call Regular Method from Inside Class

Not possible

self.method()

From Codeium:

When you access an attribute with self, Python first looks for it in the instance's namespace. If it doesn't find it there, it then checks in the class namespace (and subsequently in the namespaces of its base classes, if any).

Define a Class

class MyClass:
	# class definition

class MyClass(ClassToInheritFrom):
	# class definition

Member Variables

Define class attributes.

class MyClass:
	class_attribute_1 = 0

	@classmethod
	def class_method(cls):
		# Change value of an existing class attribute.
		cls.class_attribute_1 = 2
		# Create a new class attribute.
		cls.class_attribute_2 = 4

Define instance variables.

class MyClass:
	self.myvar1 = 2
	
	def __init__(self):
		self.myvar2 = 6

Methods

Class methods, instance methods, and static methods:

class MyClass:
	@classmethod
	def class_method(cls, arg1, arg2):
		# Must only pass `cls`.
		# You can't pass `self` (the instance) to
		# a class method because there's no instance.
		print("This is a class method")
	
	def regular_method(self, arg1, arg2):
		# Must only pass `self`.
		print("This is a regular method")
	
	@staticmethod
	def static_method(arg1, arg2):
		# Cannot pass `cls` or `self`.
		# Has no access to class or instance.
		print("This is a regular method")

Accessing from Outside

Class attributes and methods can be accessed using either the class name or instance name.

The class name cannot be used to access instance member variables and methods.

class MyClass:
	class_attribute = 0

	@classmethod
	def class_method(cls):
		print("hello world")

# Access using class name.
print(MyClass.class_attribute)
MyClass.class_method()

# Access using instance name.
instance = MyClass()
print(instance.class_attribute)
instance.class_method()

Instance member variables and regular methods can be accessed only using the instance name. They cannot be accessed using the class name.

class MyClass:
	self.myvar1 = 2
	
	def __init__(self):
		self.myvar2 = 6

	def print_vals(self):
		print(self.myvar1)
		print(self.myvar2)

# Access using instance name.
instance = MyClass()
print(instance.myvar1)
instance.print_vals()

The values of class attributes will persist throughout the program, as instances of the class come and go. Instance member variables and methods live only within the instance.

Accessing from Inside

class MyClass:
	# Class attribute
	class_attribute = 140
	# Instance variable
	self.myvar1 = 0
	
	# Instance constructor
	def __init__(self):
		self.myvar2 = 6
	
	# Class method
	@classmethod
	def class_method(cls):
		# Access class attribute
		print(cls.class_attribute)
		# Access instance variable
		self.myvar1 = 2
		# Check and get class attribute
        if hasattr(MyClass, 'class_attribute'):
	        temp = getattr(MyClass, 'class_attribute')
	        setattr(MyClass, 'class_attribute', 17)
	
	# Instance method
	def print_vals(self):
		# Access instance variables
		print(self.myvar1, self.myvar2)
		# Access class attribute
		print(type(self).class_attribute)
		# Set instance variable
        setattr(self, 'myvar2', 43)
        # Set class attribute
        setattr(MyClass, 'class_attribute', 17)
	
	# Static method
	@staticmethod
	def print_text(text_to_print: str):
		print(text_to_print)

Using Attribute Functions

class MyClass:
	attr1 = 0
	self.var1 = 0

From either inside or outside class def:

hasattr(MyClass, "attr1")
getattr(MyClass, "attr1")
setattr(MyClass, "attr1", 3)
delattr(MyClass, "attr1")

Only from inside class def:

hasattr(self, "var1")
getattr(self, "var1")
setattr(self, "var1", 3)
delattr(self, "var1")
def instance_method(self):
	hasattr(self, "var1")
	getattr(self, "var1")
	setattr(self, "var1", 3)
	delattr(self, "var1")
@classmethod
def class_method(cls):
	hasattr(cls, "attr1")
	getattr(cls, "attr1")
	setattr(cls, "attr1", 3)
	delattr(cls, "attr1")
hasattr(type(self), "attr1")
getattr(type(self), "attr1")
setattr(type(self), "attr1", 3)
delattr(type(self), "attr1")

Only from outside class def:

intance = MyClass()
hasattr(instance, "var1")
getattr(instance, "var1")
setattr(instance, "var1", 3)
delattr(instance, "var1")
intance = MyClass()
hasattr(type(instance), "attr1")
getattr(type(instance), "attr1")
setattr(type(instance), "attr1", 3)
delattr(type(instance), "attr1")

Last updated 11 months ago

@classmethod
def cls_method(cls):
def inst_method(self):
MyClass.var1 = 3
a = MyClass()
a.var1 = 3
# or
MyClass.var1 = 3
cls.var1 = 3
# or
MyClass.var1 = 3
cls.var1 = 3
# or
MyClass.var1 = 3
# or
type(self).var1 = 3
# or
self.var1 = 3
a = MyClass()
a.var1 = 3
self.var1 = 3
MyClass.method()
a = MyClass()
a.method()
# or
MyClass.method()
cls.method()
# or
MyClass.method()
cls.method()
# or
MyClass.method()
# or
type(self).method()
# or
self.method()
a = MyClass()
a.method()