How do you define a class in python

Here's a simple example of a class:class Animal: def init(self, name, noise): self.name = name self.noise = noise def make_noise(self): print(self.noise) here init is the "initializer" (or sometimes called the "constructor") of the class. This gets run when a new instance of the class is created. make_noise is one of the class's methods, which prints the noise the animal makes. You use this method on an instance of the class. Python passes the instance of the class being called as the first argument to any of the functions in the class, this is what we're calling "self". So in the following example:dog = Animal("dog", "bark") dog.make_noise() dog, "dog" and "bark" are used as the self, name and noise parameters in init, and dog is passed as the self parameter in make_noise. So this program would output "bark".

WP
Answered by William P. Python tutor

1396 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

Creating string from multiple strings(or characters)


Write a function that checks whether a number is prime or not.


Firstly, my question is not Python related, but maths A-level related. I don't know how to change that in my profile but I would like to only tutor maths GCSE and potentially A-level. My question: Integrate sin(x)^3 over x=0 and x=pi/2.


What is the difference between using range() and a list of values?


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo

© MyTutorWeb Ltd 2013–2025

Terms & Conditions|Privacy Policy
Cookie Preferences