Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

how to make a class in python

class Person:
  def __init__(self, _name, _age):
    self.name = _name
    self.age = _age
   
  def sayHi(self):
    print('Hello, my name is ' + self.name + ' and I am ' + self.age + ' years old!')
    
p1 = Person('Bob', 25)
p1.sayHi() # Prints: Hello, my name is Bob and I am 25 years old!
Comment

python class

class Person:
    # class static variable
    person_type = "Human"

    # class constructor
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    # initialized class method
    def get_full_name(self):
        return f"{self.first_name} {self.last_name}"

    # initialized class method
    def introduce(self):
        return f"Hi. I'm {self.first_name} {self.last_name}. I'm {self.age} years old."

    # class static method
    @staticmethod
    def class_name(self):
        return 'Person'

    # class method
    @classmethod
    def create_anonymous(cls):
        return Person('John', 'Doe', 25)

    # dunder method - return class as a string when typecast to a string
    def __str__(self):
        return f"str firstname: {self.first_name} lastname: {self.last_name} age: {self.age}"

    # dunder method - return class a string then typecast to representative
    def __repr__(self):
        return f"repr firstname: {self.first_name} lastname: {self.last_name} age: {self.age}"

    # dunder method - return sum of ages when using the + operator on two Person classes
    def __add__(self, other):
        return self.age + other.age


# create a person class
bob = Person(first_name="John", last_name="Doe", age=41)

# print static method
print(Person.class_name(Person))

# print new class person
print(Person.create_anonymous().get_full_name())

# print class static method
print(Person.person_type)

# print string representation of class
print(bob)

# print representation of class
print(repr(bob))

# add Person classes ages using dunder method
print(bob + bob)
Comment

create and use python classes

class Mammal:
    def __init__(self, name):
        self.name = name

    def walk(self):
        print(self.name + " is going for a walk")


class Dog(Mammal):
    def bark(self):
        print("bark!")


class Cat(Mammal):
    def meow(self):
        print("meow!")


dog1 = Dog("Spot")
dog1.walk()
dog1.bark()
cat1 = Cat("Juniper")
cat1.walk()
cat1.meow()
Comment

python class

class Person:#set name of class to call it 
  def __init__(self, name, age):#func set ver
    self.name = name#set name
    self.age = age#set age
   

    def myfunc(self):#func inside of class 
      print("Hello my name is " + self.name)# code that the func dose

p1 = Person("barry", 50)# setting a ver fo rthe class 
p1.myfunc() #call the func and whitch ver you want it to be with 
Comment

python classes


class Box(object): #(object) ending not required
  def __init__(self, color, width, height): # Constructor: These parameters will be used upon class calling(Except self)
    self.color = color # self refers to global variables that can only be used throughout the class
    self.width = width
    self.height = height
    self.area = width * height
  def writeAboutBox(self): # self is almost always required for a function in a class, unless you don't want to use any of the global class variables
    print(f"I'm a box with the area of {self.area}, and a color of: {self.color}!")

greenSquare = Box("green", 10, 10) #Creates new square
greenSquare.writeAboutBox() # Calls writeAboutBox function of greenSquare object
Comment

class python

class MyClass(object):
  def __init__(self, x):
    self.x = x
Comment

python class

# Standard way of writing a simple class
class Person1:
# Type hinting not required
    def __init__(self, name: str, age: int, num_children=0):
        self.name = name
        self.age = age
        self.num_children = num_children

    def __repr__(self):
        return f'My name is {self.name}, I am {self.age} years old, and I have {self.num_children} children'

      
from dataclasses import dataclass


# A class using data classes. Dataclasses are simpler but can't support operations during initialization
@dataclass()
class Person2:
    """ This class handles the values related to a person. """
    name: str  # Indicating types is required
    age: int
    num_children = 0  # Default values don't require an indication of a type

    def __repr__(self):
        return f'My name is {self.name}, I am {self.age} years old, and I have {self.num_children} children'

# Both classes (Person1 and Person2) achieve the same thing but require different code to do it

person1 = Person1('Joe', 28, 2)
print(person1)
# Result: My name is Joe, I am 28 years old, and I have 2 children

person2 = Person2('Emma', 19)
print(person2)
# Result: My name is Emma, I am 19 years old, and I have 0 children
Comment

python define class

class uneclasse():
  def __init__(self):
    pass
  def something(self):
    pass
xx = uneclasse()
xx.something()
Comment

python class

class Animal(object): # Doesn't need params but put it there anyways.
    def __init__(self, species, price):
        self.species = species # Sets species name
        self.price = price # Sets price of it
    
    def overview(self): # A function that uses the params of the __init__ function
        print(f"This species is called a {self.species} and the price for it is {self.price}")

class Fish(Animal): # Inherits from Animal
    pass # Don't need to add anything because it's inherited everything from Animal
 
salmon = Fish("Salmon", "$20") # Make a object from class Fish
salmon.overview() # Run a function with it
dog = Animal("Golden retriever", "$400") # Make a object from class Animal
dog.overview() # Run a function with it
Comment

class python

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

p1 = Person("John", 36)

p1.age = 40

print(p1.age)
---------------------------------------------------------------
40
Comment

how to declare a class in python

class ClassName(object): #"(object)" isn't mandatory unless this class inherit from another
  	def __init__(self, var1=0, var2):
    
    	#the name of the construct must be "__init__" or it won't work
    	#the arguments "self" is mandatory but you can add more if you want 
    	self.age = var1
    	self.name = var2
    
    	#the construct will be execute when you declare an instance of this class
    
  	def otherFunction(self):
    	
        #the other one work like any basic fonction but in every methods,
    	#the first argument (here "self") return to the class in which you are
 	
Comment

python classes

class Student:
  def __init__(self, id, name, age):
    self.name = name
    self.id = id
    self.age = age
  
  def greet(self):
    print(f"Hello there.
My name is {self.name}")
    
  def get_age(self):
    print(f"I am {self.age}")
    
  def __add__(self, other)
  	return Student(
      self.name+" "+other.name,
      self.id + " "+ other.id,
      str(self.age) +" "+str(other.age))
    
p1 = Student(1, "Jay", 19)
p2 = Student(2, "Jean", 22)
p3 = Student(3, "Shanna", 32)
p4 = Student(4, "Kayla", 23)


result = p1+p3
Comment

class python

class Employee(Object)
	def __init__(self, name, age, salary):
    	self.name = name
      	self.age = age
        self.salary = salary
        
        
  
  	def __str__(self)
    return f"Employee {name} 
hes age {age} 
and make {salary}"
Comment

classes in python

# plz suscribe to my youtube channel -->
# https://www.youtube.com/channel/UC-sfqidn2fKZslHWnm5qe-A

class Fan:

    def __init__(self, company, color, number_of_wings):
        self.company = company
        self.color = color
        self.number_of_wings = number_of_wings
        
    def PrintDetails(self):
        print('This is the brand of',self.company,'its color is', self.color,' and it has',self.number_of_wings,'petals')
    
        
    def switch_on(self):
        print("fan started")
        
    def switch_off(self):
        print("fan stopped")
        
    def speed_up(self):
        print("speed increased by 1 unit")
        
    def speed_down(self):
        print("speed decreased by 1 unit")
        
usha_fan = Fan('usha','skin',5)
fan = Fan('bajaj','wite', 4)


print('these are the details of this fan')
usha_fan.PrintDetails()
print()

usha_fan.switch_on()
Comment

python class

class Human():
    def __init__(self, _name, _age):
        self.name = _name
        self.age = _age

    def walk(self):
        print("walking...")

Person = Human('John', 32)
Person.walk()
Comment

what is a class in python

A class is a block of code that holds various functions. Because they
are located inside a class they are named methods but mean the samne
thing. In addition variables that are stored inside a class are named 
attributes. The point of a class is to call the class later allowing you 
to access as many functions or (methods) as you would like with the same
class name. These methods are grouped together under one class name due
to them working in association with eachother in some way.
Comment

python class


class Dog(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def speak(self):
        print("Hi I'm ", self.name, 'and I am', self.age, 'Years Old')

JUB0T = Dog('JUB0T', 55)
Friend = Dog('Doge', 10)
JUB0T.speak()
Friend.speak()
Comment

how to define a class in python

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

    def say_name(self):
      print(f"Hello, I am {self.name}")

p1 = Person("Sara", 18)
p1.say_name() 
Comment

Class in python

# Node class
class Node:
  
    # Function to initialize the node object
    def __init__(self, data):
        self.data = data  # Assign data
        self.next = None  # Initialize
                          # next as null
  
# Linked List class
class LinkedList:
    
    # Function to initialize the Linked
    # List object
    def __init__(self):
        self.head = None
Comment

classes in python

class Foo:
  def __init__(self):
    self.definition = Foo!
  def hi():
    # Some other code here :)
    
# Classes require an __init__ if you want to assign attributes. (self) defines what describes the attribs.
      
Comment

objects and classes in python

class IntellipaatClass:
	a = 5
	def function1(self):
		print(‘Welcome to Intellipaat’)
#accessing attributes using the class object of same name
IntellipaatClass.function(1)
print(IntellipaatClass.a)
Comment

class in python

class LuckyLemur():
  	def __init__(self, description):
		self.description = description
	
    def reveal_description(self):
    	print(f'Lucky Lemur is {self.description}')

lucky_lemur = LuckyLemur('Pro')
lucky_lemur.reveal_description()
Comment

python class

class Dog:

    def bark(self):
        print("Woof!")

    def roll(self):
        print("*rolling*")

    def greet(self):
        print("Greetings, master")

    def speak(self):
        print("I cannot!")

# Creating the Dog class instance and saving it to the variable <clyde>
clyde = Dog()
clyde.bark()   # --> Woof!
clyde.roll()   # --> *rolling*
clyde.greet()  # --> Greetings, master
clyde.speak()  # --> I cannot!

# Creating another Dog instance
jenkins = Dog()
jenkins.bark()  # --> Woof!
jenkins.roll()  # --> *rolling*
# .. And other methods
# .. Infinite objects can be created this way, all implementing the same methods defined in our class
Comment

how to use a class in python

class awwab(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def speak(self):
        print("Hello, my name is",self.name,"and I am",self.age,"years old!")
        
awwabasad = awwab("Awwab Asad", 11)
print(awwabasad.speak())
Comment

Python classes and objects

class Person:
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender

    def greet(self, person_to_greet):
        # person_to_greet will be another Person object
        print(f"Hey {person_to_greet.name}, nice to meet you I'm {self.name}")

    def ask_age(self, ask_from):
        print(f"{self.name}: {ask_from.name}, How old are you?")
        print(f"{ask_from.name}: i am {ask_from.age}")


# Creating a person object
tom = Person("Tom", 50, "Male")

# we can also create an object with keyword arguments
jack = Person(name="Jack", age=19, gender="Male")

# Here we call the greet method of tom, and we pass the Jack Person Object Created above
tom.greet(jack)

# if we call the greet method of jack and pass the Tom person object, then jack greets tom
jack.greet(tom)

# Here Jack will ask age of tom, and tom will reply with his age
jack.ask_age(tom)
Comment

Python Class Example

#Source: https://vegibit.com/python-class-examples/
class Vehicle:
    def __init__(self, brand, model, type):
        self.brand = brand
        self.model = model
        self.type = type
        self.gas_tank_size = 14
        self.fuel_level = 0

    def fuel_up(self):
        self.fuel_level = self.gas_tank_size
        print('Gas tank is now full.')

    def drive(self):
        print(f'The {self.model} is now driving.')

obj = Vehicle("Toyota", "Carola", "Car")
obj.drive()
Comment

Python class example

class Greet:
	def __init__(self, names):
    	self.names = names

	def say_hello(self):
    	for name in self.names:
        	print("Hello " + name)
Comment

simple python class

class Person:
    def say_hi(self):
        print('Hello, how are you?')

p = Person()
p.say_hi()
# The previous 2 lines can also be written as
# Person().say_hi()
Comment

class method in python

# Python program to demonstrate
# use of a class method and static method.
from datetime import date
  
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
  
    # a class method to create a
    # Person object by birth year.
    @classmethod
    def fromBirthYear(cls, name, year):
        return cls(name, date.today().year - year)
  
    # a static method to check if a
    # Person is adult or not.
    @staticmethod
    def isAdult(age):
        return age > 18
  
person1 = Person('mayank', 21)
person2 = Person.fromBirthYear('mayank', 1996)
  
print(person1.age)
print(person2.age)
  
# print the result
print(Person.isAdult(22))
Comment

python how to create a class

class class_name:
	def __init__(self):
    	# class variables(can be used all over the class)
        pass
first_class = class_name() # creating the class
Comment

classes in python

>>> print(ObjectCreator) # you can print a class because it's an object
<class '__main__.ObjectCreator'>
>>> def echo(o):
...       print(o)
...
>>> echo(ObjectCreator) # you can pass a class as a parameter
<class '__main__.ObjectCreator'>
>>> print(hasattr(ObjectCreator, 'new_attribute'))
False
>>> ObjectCreator.new_attribute = 'foo' # you can add attributes to a class
>>> print(hasattr(ObjectCreator, 'new_attribute'))
True
>>> print(ObjectCreator.new_attribute)
foo
>>> ObjectCreatorMirror = ObjectCreator # you can assign a class to a variable
>>> print(ObjectCreatorMirror.new_attribute)
foo
>>> print(ObjectCreatorMirror())
<__main__.ObjectCreator object at 0x8997b4c>
Comment

python class

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'
Comment

classes in python

fromr random import radint

Asnwer= randint(1,200)
count= 0

while true:
  guess  = getingeger("whatis yourestimate")
  if guess< 1 or guess > 200:
    print(your estimate must be between 1 and 200)
    
    continue
    
  count+ = 1
  if guess < answer:
    print("higher")
  elif guess > answer:
    print("lower")
  else:
    print("you guessed it!")
    
if count== 1
	print("wow first try!!")

  else:
    print("you estimated it in, count,'time'")
Comment

class python

"""
:return : Simple class methods with an alternative constructor, just only take
		  an input of the data in the form of string and return it into the 
          instance variable.
"""

class Employees:
    no_of_leaves = 8

    def __init__(self, _age, _name, _leave, _salary, _work_experience):
        self.name = _name
        self.age = _age
        self.leave = _leave
        self.salary = _salary
        self.work_experience = _work_experience
        
    @classmethod
    def alternative__constructor_class(cls, _input_string):
        """
        :param _input_string: Takes the input from the function from the class,
        :return: The alternative__constructor works to add data only one string and then,
                 return it into the object.
        :parameter: Class methods as the alternative constructor.

        """

        # params_split = _input_string.split("-")
        # print(params_split)
        # return cls(params_split[0], params_split[1], params_split[2], params_split[3], params_split[4])
        # Multi liner functions
        return cls(*_input_string.split("-"))

    @classmethod
    def change_leave_class_method(cls, _new__leave):
        cls.no_of_leaves = _new__leave

    def return__employee_statement(self):
        return f"Name : {self.name} Age : {self.age} leave : {self.leave} salary : {self.salary}" 
               f"Work Experience : {self.work_experience}"


anshu = Employees(_name="Anshu", _salary=70000, _leave=8, _work_experience=6, _age=16)
shivam = Employees.alternative__constructor_class("shivam-16-7000-4-2")
print(shivam.return__employee_statement())

anshu.change_leave_class_method(30)
print(Employees.no_of_leaves)
Comment

what is a class in python

# plz suscribe to my youtube channel -->
# https://www.youtube.com/channel/UC-sfqidn2fKZslHWnm5qe-A

Classes are blueprint used to construct objects
Comment

python classes and objects

class employee:
    name = ''
    id = 0
    department = ''

    def pay(self):
        print(self.name, self.id, self.department)


s = employee()
s.name = 'burhan'
s.id = 0o2234523
s.department = 'Development'
s.pay()

b = employee()
b.name = 'Abdullah'
b.id =12423432857
b.department = 'Software Engineer'
b.pay()

c = employee()
c.name = 'Bilal'
c.id =12423432857
c.department = 'Software Engineer'
c.pay()
Comment

Defining a Class in Python

class MyNewClass:
    '''This is a docstring. I have created a new class'''
    pass
Comment

can you make a class in a class python

# Yes 
class Main:
  # outer class
  class Inner():
    # inner class
    pass
Comment

class python example

def ok(index):
    print(index) > Hi!
ok("Hi!")
class Lib:
    def ok(self,Token):
        print(Token) > Hello World!
Library = Lib()
Library.ok("Hello World!")
Comment

classes in python

class fruit:
  def __init__(self,color,taste,name):
    self.color = color
    self.name = name
    self.taste = taste
    
    def myfunc(self):
      print("{} = Taste:{}, Color:{}".format(self.name, self.taste, self.color))
      
f1 = fruit("Red", "Sweet", "Red Apple")
f1.myfunc()
Comment

python class

class Car():
    def __init__(self, _name, _year):
        self.name = _name
        self.age = _age

    def start(self):
        print("starting...")
        
    def drive(self):
    	print("Vroom Vroom!")

myCar = Car('Audi', 2019)
myCar.start()
myCar.drive()
Comment

python class declaration

#Testing
class Class_Def:
  def __init__(self):
    pass
Comment

PREVIOUS NEXT
Code Example
Python :: python choose sample from list with replacement 
Python :: python break long string multiple lines 
Python :: how to check if given number is binary in pytho 
Python :: pandas dataframe delete column 
Python :: flatten nested list 
Python :: how to pause time in python 
Python :: install virtual environment python mac 
Python :: is power of python recursion 
Python :: set size of button tkinter 
Python :: Renaming an index in pandas data frame 
Python :: modify string in column pandas 
Python :: geometrical mean python 
Python :: what does ^ do python 
Python :: how to change os path in python 
Python :: round down python 
Python :: Palindrome Check using for loop in python 
Python :: python tensorflow is not defined 
Python :: pandas read cell value by index and column name 
Python :: internal server error 500 python flask 
Python :: what should you call a decimal value in python 
Python :: pandas not in list 
Python :: python list comprehension elif 
Python :: define empty numpy array 
Python :: python print raw string 
Python :: python get latest edited file from any directory 
Python :: python resize image in tkinter 
Python :: how to hide a widget in tkinter python 
Python :: matplotlib cheatsheet 
Python :: extend tuple python 
Python :: how to resize windows in python 
ADD CONTENT
Topic
Content
Source link
Name
7+9 =